#include "formpzlr.h"
#include "ui_formpzlr.h"
#include <mysql.h>
#include <formcam.h>
#include <formpz_fpcy.h>
#include <formpz_fj.h>
#include <QDebug>
#include <QLineEdit>
#include <QAbstractItemView>

#include <QScrollBar>
#include <QPalette>
#include <QDate>
#include <QInputDialog>
#include <QFileDialog>
#include <QLabel>
#include <QWidget>
FormPZLR::FormPZLR(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormPZLR)
{
    ui->setupUi(this);
    this->setMinimumSize(1280,700);
    this->show();
    Start();
    RefTree();
    //setFocusPolicy(Qt::StrongFocus);
    ui->txtInput->setFocusPolicy(Qt::StrongFocus);
    this->setFocusPolicy(Qt::StrongFocus);
    //ui->txtInput->installEventFilter(this);  //在窗体上为lineEdit1安装过滤器
    ui->txtInput->setVisible(false);
    ui->treeWidget->setVisible(false);
    ui->widgetXM->setVisible(false);

    QPalette pal(ui->widgetXM->palette());
    QColor color;
    color.setRgb(255, 255, 240,255);
    pal.setColor(QPalette::Background, color);

    ui->widgetXM->setAutoFillBackground(true);
    ui->widgetXM->setPalette(pal);
    ui->widgetXM->setWindowFlags(Qt::FramelessWindowHint);
    //ui->treeWidgetXM->expandAll();
    ui->treeWidgetXM->collapseAll();
    //ui->widgetXM->show();
    //ui->widgetXM->setStyleSheet("::title{background-color:white}");
    ui->tablePZ->setContextMenuPolicy(Qt::CustomContextMenu);       // 右键使能
    menu = new QMenu(ui->tablePZ);
       addRow = new QAction(menu);
       addRow->setText("新增一行");
       reRow = new QAction(menu);
       reRow->setText("删除一行");
       menu->addAction(addRow);
       menu->addAction(reRow);

       QObject::connect(ui->tablePZ, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenuPos(QPoint)));
       QObject::connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(MenuSlot(QAction*)));

}
void FormPZLR::Start()
{
    QString QX=mySQL::Permission; //读取权限
    if (QX.mid(10,1)=="0"){ //创建会计年度
        ui->btnFHRZ->setEnabled(false);
    }
    //保存按钮使能
    ui->btnSave->setEnabled(true);
    //ui->tablePZ->height()=lineHeight*8;
    ui->tabWidget->setTabPosition(QTabWidget::West);//设置选项卡的方位东南西北，这次选中在西边
    ui->tabWidget->setTabText(0,"凭证内容");
    ui->tabWidget->setTabText(1,"附件");
    ui->tabWidget->setTabText(2,"电子发票");
    ui->tabWidget->setCurrentIndex(0);
    ui->tabWidget->setStyleSheet("QTabBar::tab { background: gray; color: white; padding: 10px; } "
                                 "QTabBar::tab:selected { background: black; } " );
    ui->treeWidgetFP->setHeaderLabels(QStringList() << "发票类型" << "发票代码" <<"发票号码" <<"金额（去税）" << "上传者" << "日期" << "原始信息" << "idd");
    ui->treeWidgetFJ->setHeaderLabels(QStringList() << "文件名"  << "上传者" << "上传日期" <<"idd" );
    ui->btnPZFJ->setVisible(false);
    QStringList list1;
    list1.clear();
    list1<<"科目代码"<<"部门/项目"<<"摘要信息"<<"借贷"<<"栏次"<<"金额"<<"外币"<<"PZID";
    QRegExp rx("^[0-9]+$");  //凭证编号只允许输入数字
    QRegExpValidator *pReg = new QRegExpValidator(rx, this);
    ui->txtPZBH->setValidator(pReg);
    ui->txtPZBH->setText("");

    ui->tablePZ->clear();
    ui->tablePZ->setColumnCount(list1.size());
    ui->tablePZ->setHorizontalHeaderLabels(list1);
    //设置列宽
    ui->tablePZ->setColumnWidth(0, 200);
    ui->tablePZ->setColumnWidth(1, 180);
    ui->tablePZ->setColumnWidth(2, 380);
    ui->tablePZ->setColumnWidth(3, 40);
    ui->tablePZ->setColumnWidth(4, 0);
    ui->tablePZ->setColumnWidth(5, 180);
    ui->tablePZ->setColumnWidth(6, 140);
    ui->tablePZ->setColumnWidth(7, 0);
    //ui->tablePZ->horizontalHeader()->setStretchLastSection(true); //设置充满表宽度
    //ui->tableWidget1->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
    ui->tablePZ->verticalHeader()->setFixedWidth(40);
    ui->tablePZ->verticalHeader()->setDefaultSectionSize(lineHeight); //设置行距
    //ui->tablePZ->horizontalHeader()->resizeSection(0,150); //设置表头第一列的宽度为150
    ui->tablePZ->horizontalHeader()->setFixedHeight(lineHeight); //设置表头的高度
    ui->tablePZ->horizontalHeader()->setStyleSheet("QHeaderView::section{background:skyblue;}");
    ui->tablePZ->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色
    ui->tablePZ->setRowCount(2); //暂时设置成2行
    ui->tablePZ->setEditTriggers(QAbstractItemView::NoEditTriggers); //不可编辑
    ui->tablePZ->setSelectionMode(QAbstractItemView::SingleSelection);//单选
    ui->tablePZ->horizontalScrollBar()->setEnabled(false);

    for (int i=0;i<2;i++) {
        ui->tablePZ->setItem(i,0,new QTableWidgetItem(""));
        ui->tablePZ->setItem(i,1,new QTableWidgetItem(""));
        ui->tablePZ->setItem(i,2,new QTableWidgetItem(""));
        ui->tablePZ->setItem(i,3,new QTableWidgetItem("借"));
        ui->tablePZ->setItem(i,4,new QTableWidgetItem(""));
        ui->tablePZ->setItem(i,5,new QTableWidgetItem("0.00"));
        ui->tablePZ->setItem(i,6,new QTableWidgetItem(""));
        ui->tablePZ->setItem(i,7,new QTableWidgetItem(""));
        ui->tablePZ->item(i,0)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(i,1)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(i,2)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(i,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
        ui->tablePZ->item(i,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
        ui->tablePZ->item(i,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        ui->tablePZ->item(i,6)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    }
    /*
    for (int i=2000;i<2100;i++){
        ui->cmbND->addItem(QString("%1").arg(i));
    }*/
    QString SQL="";
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    SQL="";
    SQL=QString("SELECT nd FROM  nd  where  type_id='%1' order by nd desc").arg(mySQL::TypeId);
    //qDebug() << SQL;
    query.exec(SQL);
    ui->cmbND->clear();
    while(query.next()){
        ui->cmbND->addItem(query.value("nd").toString());
    }
    ui->cmbND->setCurrentText(mySQL::ND);
    ui->cmbND->setEnabled(false);
    ui->cmbYF->clear();
    for (int i=1;i<12;i++){
        ui->cmbYF->addItem(QString("%1").arg(i,2,10,QChar('0'))); //变量，2位，十进制，替代空字符 如果10 变成2 就变成2进制的了
     }
    QString ND=ui->cmbND->currentText().trimmed();

    ui->treeWidgetWH->clear();
    ui->treeWidgetWH->setHeaderLabels(QStringList() << "类型" << "货币名称" << "简称"  << "汇率"  );
    ui->treeWidgetWH->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
    SQL=QString("SELECT lx,hbmc,hbjc,hl FROM `hl` WHERE type_id='%1' and nd='%2' order by lx desc ").arg(mySQL::TypeId).arg(ND) ;
    query.exec(SQL);
    while(query.next()){
        QStringList child;
        child.clear();
        child << query.value("lx").toString();
        child << query.value("hbmc").toString();
        child << query.value("hbjc").toString();
        child << query.value("hl").toString();
        QTreeWidgetItem * citem =new QTreeWidgetItem(child);
        ui->treeWidgetWH->addTopLevelItem(citem);
        ui->cmbHB->addItem(query.value("hbjc").toString());

    }
    ui->txtHL->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
    ui->txtWB->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);


    ui->txtDJ->setText("1");
    ui->txtDJ->setAlignment(Qt::AlignCenter);
    ui->txtPZBH->setAlignment(Qt::AlignCenter);
    ui->cmbPZLX->clear();
    ui->cmbPZLX->addItem("现金凭证");
    ui->cmbPZLX->addItem("转账凭证");
    ui->cmbPZLX->addItem("其他凭证");
    SQL=QString("SELECT COUNT(*) AS `行数`, `pzlx` FROM `pzzb`  WHERE type_id='%1'  GROUP BY `pzlx` ORDER BY `pzlx` ").arg(mySQL::TypeId);
    query.exec(SQL);
    while(query.next()){
        ui->cmbPZLX->addItem(query.value("pzlx").toString().trimmed());
    }
    ui->dtPZRQ->setDate(QDate::currentDate());
    ui->labZT->setWordWrap(true); //可以换行
    ui->labZT->setAlignment(Qt::AlignBottom);
    ui->labJD->setAlignment(Qt::AlignBottom);
    this->setWindowTitle("凭证录入");
    ui->txtInput->setVisible(false);
    ui->treeWidget->setVisible(false);
    ui->widgetXM->setVisible(false);
    ui->groupWB->setVisible(false);
    ui->groupWH->setVisible(false);
    ui->txtPZBH->setEnabled(false);
    //ui->groupDZFP->setVisible(false);
    ui->cmbFPLX->clear();
    ui->cmbFPLX->addItem("01-增值税专用发票");
    ui->cmbFPLX->addItem("04-增值税普通发票");
    ui->cmbFPLX->addItem("10-增值税电子普通发票");
    ui->cmbFPLX->setCurrentIndex(0);

}
bool FormPZLR::RefJD()
{
    //刷新借贷信息 顺便检查一下凭证输入有没有问题
    double JF=0;
    double DF=0;
    QString JD="";
    QString tmpStr="";
    bool Rreturn=true;

    //ui->tablePZ 遍历读取数据
    for(int i=0;i<ui->tablePZ->rowCount();i++){
        //先判断是否最末一级科目
        XMBH="";

        if(ui->tablePZ->item(i,0)!=NULL && ui->tablePZ->item(i,0)->text().trimmed()!="" ){
            QTreeWidgetItemIterator it(ui->treeWidget);
            QString str=ui->tablePZ->item(i,0)->text();
            if(str!=""){
                str=str.left(str.indexOf("-"));
            }
            int itemCount=10;
            while (*it) {
                //if  ((*it)->text(0).left(str.length())==str){
                if  ((*it)->text(0)==str){
                    itemCount=(*it)->childCount(); //子项目的数量 为0即为末级，所以初始化为10
                    if ((*it)->text(2)=="项目核算" &&  (*it)->text(3)!=""){
                        XMBH=(*it)->text(3);
                    }
                }
                ++it;
            }
           if (itemCount!=0){
               if (tmpStr!=""){
                  tmpStr+="\n" ;
               }
               tmpStr+=QString("第%1行:科目代码:%2 无效！或存在下级！！！").arg(i+1).arg(str);
               Rreturn=false;
               //QMessageBox::warning(this,"警告",QString("科目代码:%1 无效！\n 或存在下级！！！").arg(str));
               //return;
           }
           if (XMBH!=""){
               //项目编号不为空的情况下开始判断项目编号是否符合规定
               QString XMMC=ui->tablePZ->item(i,1)->text();
               QStringList sl1 =XMBH.split(",");
               QStringList sl2 =XMMC.split(",");
               for (int j=0; j<sl1.count(); j++){
                   if (sl1[j].left(1) != sl2[j].left(1)){
                       if (tmpStr!=""){
                          tmpStr+="\n" ;
                       }
                       tmpStr+=QString("第%1行:项目无效，请重新选择！").arg(i+1);
                   }
               }
           }else{
              //项目编号为空即将原有项目编号清空
               ui->tablePZ->item(i,1)->setText("");
           }
        }
        JD=ui->tablePZ->item(i,3)->text();
        if(ui->tablePZ->item(i,5)!=NULL) {

            if (JD=="借"){
                JF+=ui->tablePZ->item(i,5)->text().toDouble();
            }
            if (JD=="贷"){
                DF+=ui->tablePZ->item(i,5)->text().toDouble();
            }
        }
    }
    ui->labJD->setText(QString("借方：%L1\n贷方：%L2\n差额：%L3").arg(QString::number(JF, 'f', 2)).arg(QString::number(DF, 'f', 2)).arg(QString::number(JF-DF, 'f', 2)));
    if (QString::number(JF-DF, 'f', 2)!="0.00"){
        if (tmpStr!=""){
           tmpStr+="\n" ;
        }
        tmpStr+=QString("借贷不平");
        Rreturn=false;
    }
    if (tmpStr!=""){
        ui->labZT->setText(tmpStr);
        //QMessageBox::warning(this,"警告",tmpStr);
    }
    return Rreturn;

}

void FormPZLR::focusInEvent(QFocusEvent *e)
{
    // qDebug() << "*MyLineEdit::focusInEvent" << this->objectName();
    QPalette pGreen = QPalette();
    pGreen.setColor(QPalette::Base,Qt::gray);    //QPalette::Base 对可编辑输入框有效，还有其他类型，具体的查看文档
    setPalette(pGreen);
    ui->txtInput->selectAll();        // 不起使用,只有在窗体获取到焦点时才有功能
    ui->txtInput->setFocus(Qt::OtherFocusReason);
    e->ignore();
}

void FormPZLR::focusOutEvent(QFocusEvent *e)
{
    QPalette pWhite = QPalette();
    pWhite.setColor(QPalette::Base,Qt::white);
    setPalette(pWhite);
    //ui->txtInput->setVisible(false);
    ui->treeWidget->setVisible(false);
    ui->widgetXM->setVisible(false);
    e->ignore();
}

void FormPZLR::keyPressEvent(QKeyEvent *keyevent){

    if(QApplication::focusWidget() == ui->txtInput) {
        int uKey = keyevent->key();
        Qt::Key key = static_cast<Qt::Key>(uKey);
        if(key==Qt::Key_Return || key==Qt::Key_Enter ){
            if ( itemC<=5 ){
                //输入回车键后并且列数小于等于5
               switch (itemC)
                   {
                       case 0 :
                           //如果是第一列就检查科目名称是否有效
                           if (KMMC==""){ //科目名称为空的话就不让继续下去
                               QMessageBox::warning(this,"警告","无效的科目代码！");
                               FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, 0));
                               return;
                           }else{
                               chkXM();
                           }
                           break;
                       case 1 :
                           //部门 项目核算
                           FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+1));
                           break;
                       case 2 :
                           //摘要信息
                           FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+1));
                           break;
                       case 3:
                           // 借贷
                           FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+2));
                           break;
                       case 4:
                           // 栏次
                           FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+1));
                           break;
                       case 5:
                           // 金额
                           //FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+1));
                           {
                               RefJD();
                               //取出核算货币方式
                               HSHB="本币";
                               QTreeWidgetItemIterator it(ui->treeWidget);
                               QString tmpKM=ui->tablePZ->item(itemR,0)->text();
                               if(tmpKM!=""){
                                   tmpKM=tmpKM.left(tmpKM.indexOf("-"));
                               }
                                   while (*it) {
                                        //(*it)->text(0);
                                       if ((*it)->text(0)==tmpKM){
                                               HSHB=(*it)->text(4);
                                       }
                                       ++it;
                                   }
                                   int tmprow = ui->tablePZ->rowCount();
                                   if (tmprow==itemR+1)
                                   {
                                       ui->tablePZ->insertRow(tmprow);
                                       ui->tablePZ->setItem(tmprow,0,new QTableWidgetItem(""));
                                       ui->tablePZ->setItem(tmprow,1,new QTableWidgetItem(""));
                                       ui->tablePZ->setItem(tmprow,2,new QTableWidgetItem(ZYXX));
                                       ui->tablePZ->setItem(tmprow,3,new QTableWidgetItem("借"));
                                       ui->tablePZ->setItem(tmprow,4,new QTableWidgetItem(""));
                                       ui->tablePZ->setItem(tmprow,5,new QTableWidgetItem("0.00"));
                                       ui->tablePZ->setItem(tmprow,6,new QTableWidgetItem(""));
                                       ui->tablePZ->setItem(tmprow,7,new QTableWidgetItem(""));
                                       ui->tablePZ->item(tmprow,0)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,1)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,2)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                                       ui->tablePZ->item(tmprow,6)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                                       ui->tablePZ->scrollToBottom();  //滚动到底部
                                   }
                                   if (ui->tablePZ->item(itemR+1, 2)->text()==""){
                                       ui->tablePZ->setItem(itemR+1,2,new QTableWidgetItem(ZYXX));
                                   }
                                   FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR+1, 0));
                           }
                           break;
                       //default:
                       //    FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, itemC+1));
                }

                }
        }
    }
    if(QApplication::focusWidget() == ui->txtWB) {
        //外汇输入框之后返回txtinput再次捕获回车用
        int uKey = keyevent->key();
        Qt::Key key = static_cast<Qt::Key>(uKey);
        if(key==Qt::Key_Return  ){
            ui->txtInput->selectAll();
            ui->txtInput->setFocus(Qt::OtherFocusReason);
        }
    }
}
void FormPZLR::chkXM()
{
    //先取出这一行的科目是否存在项目管项目编号
    XMBH="";
    QTreeWidgetItemIterator it(ui->treeWidget);
    QString tmpKM=ui->tablePZ->item(itemR,0)->text();
    if(tmpKM!=""){
        tmpKM=tmpKM.left(tmpKM.indexOf("-"));
    }
        while (*it) {
             //(*it)->text(0);
            if ((*it)->text(0)==tmpKM){
                if ((*it)->text(2)=="项目核算" &&  (*it)->text(3)!=""){
                    XMBH=(*it)->text(3);
                }
            }
            ++it;
        }
    if (XMBH==""){ //项目编号为空则跳导摘要
        FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, 2));
    }else{
        //弹出项目选择的窗口
        ui->txtXMMB->setText(XMBH);
        QString SQL="";
        QString SS=" 1=2 ";
        QString ND=ui->cmbND->currentText();
        QStringList sl =XMBH.split(".");
        for (int i=0; i<sl.count(); i++)
        {
            //qDebug() << sl.at(i);
            SS+=QString(" or xmdm like '%1%'").arg(sl.at(i));
        }
        ui->treeWidgetXM->clear();
        ui->treeWidgetXM->setHeaderLabels(QStringList() << "项目代码" << "项目简称"  << "项目名称" << "助记码" );
        ui->treeWidgetXM->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
        SQL+=QString("SELECT xmdm,xmmc,xmjc,xmzj FROM `hsxm` WHERE type_id='%1' and nd='%2' and (").arg(mySQL::TypeId).arg(ND)+ SS+ ") order by xmdm ";
        //qDebug() << SQL;
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        query.exec(SQL);
        while(query.next()){
            QString str=query.value("xmdm").toString().trimmed();
            QStringList child;
             child.clear();
             child << query.value("xmdm").toString();
             child << query.value("xmjc").toString();
             child << query.value("xmmc").toString();
             child << query.value("xmzj").toString();
             QTreeWidgetItem * citem =new QTreeWidgetItem(child);
             if (str.length() ==1){
                 ui->treeWidgetXM->addTopLevelItem(citem);
                 ui->treeWidgetXM->expandAll();
             }else{
                 //遍历找出父节点
                 bool f=false;
                 QTreeWidgetItemIterator it(ui->treeWidgetXM);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-1)){
                             (*it)->addChild(citem);
                             f=true;
                         }
                         ++it;
                     }
                     if(f==false){
                         //如果减一个字符没照到上级 就减2个字符
                         QTreeWidgetItemIterator it(ui->treeWidgetXM);
                         while (*it) {
                              //(*it)->text(0);
                             if ((*it)->text(0)==str.left(str.length()-2)){
                                 (*it)->addChild(citem);
                                 f=true;
                             }
                             ++it;
                         }
                     }
                     if(f==false){
                         //如果减2个字符没照到上级 就减3个字符
                         QTreeWidgetItemIterator it(ui->treeWidgetXM);
                         while (*it) {
                              //(*it)->text(0);
                             if ((*it)->text(0)==str.left(str.length()-3)){
                                 (*it)->addChild(citem);
                                 f=true;
                             }
                             ++it;
                         }
                     }
             }
        }
        ui->txtXMBH->setText("");
        ui->txtXMMC->setText("");

        QString PZXM=ui->tablePZ->item(itemR,1)->text().trimmed();
        if (PZXM!=""){
            QStringList sl =PZXM.split(",");
            QString returnstr="";
            QString jstr="";
                for (int i=0; i<sl.count(); i++){
                    if (sl[i]!=""){
                        QStringList sl1 =sl[i].split(".");
                        QString str=sl1[0];
                        QTreeWidgetItemIterator it(ui->treeWidgetXM);
                            while (*it) {
                                if (str.left(1)==(*it)->text(0).left(1)){
                                    //先找到第一个字符相同的项目代码
                                    if ((*it)->childCount()==0){
                                        //如果是最末一级则先设置unchecked
                                        (*it)->setCheckState (0, Qt::Unchecked);
                                    }
                                    if (str==(*it)->text(0)){
                                        (*it)->setCheckState (0,Qt::Checked);
                                        jstr+="";
                                        jstr+=(*it)->text(0);
                                        jstr+=",";
                                        returnstr+=(*it)->text(0);
                                        returnstr+=".";
                                        returnstr+=(*it)->text(2);
                                        returnstr+=",";
                                        (*it)->setExpanded(true);
                                        //(*it)->setSelected(true);
                                        //ui->treeWidgetXM->expandItem((*it));
                                        //ui->treeWidgetXM->expandAll();
                                    }else{
                                        (*it)->setData(0, Qt::CheckStateRole, QVariant());
                                    }
                                }
                                ++it;
                            }
                    }
                }
                returnstr=returnstr.left(returnstr.length()-1);
                jstr=jstr.left(jstr.length()-1);
                ui->txtXMBH->setText(jstr);
                ui->txtXMMC->setText(returnstr);


        }else{
            //只有最末一级显示check框
            QTreeWidgetItemIterator it(ui->treeWidgetXM);
                while (*it) {
                    if ((*it)->childCount()==0){
                        (*it)->setCheckState (0, Qt::Unchecked);
                    }
                    ++it;
                }
        }

        //只有最末一级显示check框
        ui->txtInput->setVisible(false);
        ui->widgetXM->setVisible(true);
        ui->treeWidget->setVisible(false);
    }
}
void FormPZLR::RefTree()
{
    ui->treeWidget->clear();
    ui->treeWidget->setHeaderLabels(QStringList() << "科目代码" << "科目名称" << "核算方式" << "核算项目" << "核算货币" << "余额方向"  );
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
    //ui->treeWidget->setStyleSheet("QTreeWidget::item{border-right: 1px solid blue;border-left: 1px solid blue;border-bottom: 1px solid blue;}"); //加表格线
    QString SQL="";
    QString ND=ui->cmbND->currentText();
    QStringList child;
    SQL=QString("SELECT kmdm,kmmc,hsfs,xmbh,hshb,ye FROM `kmxx` WHERE type_id='%1' and nd='%2' order by kmdm").arg(mySQL::TypeId).arg(ND);
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    query.exec(SQL);
    while(query.next()){
        QString str=query.value("kmdm").toString().trimmed();
         child.clear();
         child << query.value("kmdm").toString();
         child << query.value("kmmc").toString();
         child << query.value("hsfs").toString();
         child << query.value("xmbh").toString();
         child << query.value("hshb").toString();
         child << query.value("ye").toString();
         QTreeWidgetItem * citem =new QTreeWidgetItem(child);
         if (str.length() ==1){
             ui->treeWidget->addTopLevelItem(citem);
         }else{
             //遍历找出父节点
             bool f=false;
             QTreeWidgetItemIterator it(ui->treeWidget);
                 while (*it) {
                      //(*it)->text(0);
                     if ((*it)->text(0)==str.left(str.length()-1)){
                         (*it)->addChild(citem);
                         f=true;
                     }
                     ++it;
                 }
                 if(f==false){
                     //如果减一个字符没照到上级 就减2个字符
                     QTreeWidgetItemIterator it(ui->treeWidget);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-2)){
                             (*it)->addChild(citem);
                             f=true;
                         }
                         ++it;
                     }
                 }
                 if(f==false){
                     //如果减2个字符没照到上级 就减3个字符
                     QTreeWidgetItemIterator it(ui->treeWidget);
                     while (*it) {
                          //(*it)->text(0);
                         if ((*it)->text(0)==str.left(str.length()-3)){
                             (*it)->addChild(citem);
                             f=true;
                         }
                         ++it;
                     }
                 }
         }
    }
}

FormPZLR::~FormPZLR()
{
    delete ui;
}
void FormPZLR::on_txtInput_textChanged(const QString &arg1)
{
    ui->treeWidget->setVisible(false);
    switch (itemC)
    {
        case 0:
            //在这里放置一个或多个语句
            if(arg1!="")
            {

                ui->treeWidget->setVisible(true);
                QTreeWidgetItemIterator it(ui->treeWidget);
                QString str="";
                QString fullKMMC="";                
                int itemCount=0;
                while (*it) {
                     //(*it)->text(0);
                    if  ((*it)->text(0).left(arg1.length())==arg1){
                        itemCount++;
                    }
                    if  (arg1.left((*it)->text(0).length())==(*it)->text(0)){
                        fullKMMC += "\\" +(*it)->text(1);
                        (*it)->setExpanded(true);
                    }else{
                        (*it)->setExpanded(false);
                    }
                    if ((*it)->text(0)==arg1){
                        (*it)->setSelected(true);
                        ui->treeWidget->scrollToItem((*it));
                        str=(*it)->text(1);                        
                    }else{
                        (*it)->setSelected(false);
                        //
                    }
                    ++it;
                }
                QString tmpstr="";
                tmpstr+= "科目："+fullKMMC;
                if (itemCount==0){
                    tmpstr= "无效的科目代码！！";
                }
                if (itemCount>1){
                   tmpstr+= QString(" 存在子科目【%1】个").arg(itemCount);
                }
                ui->labZT->setText(tmpstr);
                KMDM="";
                KMMC="";
                if (itemCount==1 && str!="" ){

                    ui->tablePZ->setItem(itemR,0,new QTableWidgetItem(QString("%1-%2").arg(arg1).arg(str)));
                    KMDM=arg1;
                    KMMC=str;

                }
            }
            break;
        case 1:
            ui->tablePZ->setItem(itemR,1,new QTableWidgetItem(arg1));

            break;
        case 2:
            ZYXX=arg1;
            ui->tablePZ->setItem(itemR,2,new QTableWidgetItem(arg1));
            break;
            //在这里放置一个或多个语句
        case 3:
             {
                QString jd=ui->tablePZ->item(itemR, 3)->text();
                QString tmpstr="借贷";
                if (tmpstr.indexOf(jd)==0){
                    jd="借";
                }
                if (jd!=ui->txtInput->text()){ //不加这个IF 会死机
                    if (jd=="借"){
                        jd="贷";
                    }else{
                        jd="借";
                    }
                    //ui->txtInput->setText(jd);
                }
                ui->txtInput->setText(jd);
                ui->tablePZ->setItem(itemR,3,new QTableWidgetItem(jd));
                FormPZLR::on_tablePZ_itemClicked(ui->tablePZ->item(itemR, 3));
                ui->tablePZ->item(itemR,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
            }
            break;
        case 4:
            //栏次
            ui->tablePZ->setItem(itemR,4,new QTableWidgetItem(arg1));
            ui->tablePZ->item(itemR,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
            break;
        case 5:
            {
                ui->tablePZ->setItem(itemR,5,new QTableWidgetItem(QString::number(arg1.toDouble(), 'f', 2)));
                ui->tablePZ->item(itemR,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                HSHB="本币";
                QTreeWidgetItemIterator it(ui->treeWidget);
                QString tmpKM=ui->tablePZ->item(itemR,0)->text();
                if(tmpKM!=""){
                    tmpKM=tmpKM.left(tmpKM.indexOf("-"));
                }

                    while (*it) {
                         //(*it)->text(0);
                        if ((*it)->text(0)==tmpKM){
                                HSHB=(*it)->text(4);
                        }
                        ++it;
                    }

                if (HSHB!="本币"){
                    if (mySQL::SendString==""){
                        mySQL::SendString="输入凭证金额生成外汇金额！";
                        ui->txtWB->setText("0.00");
                        QString tmpje=ui->tablePZ->item(itemR,5)->text();
                        if (tmpje!="0.00"){
                            double je=tmpje.toDouble();
                            double hl=ui->txtHL->text().toDouble();
                            ui->txtWB->setText(QString::number(je/hl, 'f', 2));
                            QString str="";
                            str+=ui->cmbHB->currentText();
                            str+="-";
                            str+=ui->txtHL->text();
                            str+="\n";
                            str+=ui->txtWB->text();
                            ui->tablePZ->item(itemR,6)->setText(str);

                        }
                        mySQL::SendString="";
                    }
                    //ui->groupWB->move(x+ui->tablePZ->columnWidth(6),y);
                    //ui->groupWB->setVisible(true);
                    //ui->txtWB->selectAll();
                    //ui->txtWB->setFocus(Qt::OtherFocusReason);
                }
            }
            break;
        //default:
        //    ui->tablePZ->setItem(itemR,itemC,new QTableWidgetItem(arg1));
        //    break;
    }

}

void FormPZLR::on_tablePZ_itemClicked(QTableWidgetItem *item)
{
    QRegExp rx("^(-?[0]|-?[1-9][0-9]{0,10})(?:\\.\\d{1,6})?$|(^\\t?$)");  //金额只允许输入2位小数 前面{0,10} 表示最大位数  后面的{1，2} 2位小数
    QRegExpValidator *pReg = new QRegExpValidator(rx, this);
    ui->txtHL->setValidator(pReg);
    ui->txtWB->setValidator(pReg);


   // QMessageBox::warning(this,"警告",tmpStr);

    //1、记录旧的单元格内容
        old_text = item->text();
        ui->treeWidget->setVisible(false);        
        ui->widgetXM->setVisible(false);
        ui->groupWB->setVisible(false);
        ui->txtInput->setVisible(false);
        if (item->text()=="" && item->column()==2){
            item->setText(ZYXX);
        }
        itemR=item->row();
        itemC=item->column();
        ui->txtInput->resize(ui->tablePZ->columnWidth(0),lineHeight);
        int colx=40;
        for (int i=0;i<item->column();i++) {
            colx+=ui->tablePZ->columnWidth(i);
            ui->txtInput->resize(ui->tablePZ->columnWidth(i+1),lineHeight);
        }
        int coly=lineHeight;
        for (int i=0;i<item->row();i++) {
            coly+=lineHeight;
        }

        int GD=ui->tablePZ->verticalScrollBar()->value();
        int maxGD=ui->tablePZ->verticalScrollBar()->maximum();
        if (GD<maxGD){
            GD++;
        }
        if (GD>=1) {
            coly=coly-(GD-1)*lineHeight;
        }
        int x=ui->tablePZ->x()+colx;
        int y=ui->tablePZ->y();
        y+=+coly;

        ui->txtInput->move(x,y);


        //ui->txtWB->setText(QString("列%1").arg(itemC));


        if (itemC==0){
           ui->treeWidget->setVisible(true);
        }

        //限制输入
        switch (itemC)
        {
            case 0:
            {

                QRegExp rx("^[A-Z0-9]+$");  //科目代码只允许输入数字和大写字母    //^[a-zA-Z0-9]+$
                QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                ui->txtInput->setValidator(pReg);
                QString str="";
                QString tmpStr=item->text();
                if (tmpStr!=""){
                    str=tmpStr.left(tmpStr.indexOf("-"));
                }
                ui->txtInput->setText(str);
                ui->txtInput->setVisible(true);
                ui->txtInput->selectAll();
                ui->txtInput->setFocus(Qt::OtherFocusReason);
                //QWidget *widget=ui->tablePZ->cellWidget(itemR,0);

                //QWidget *WidgetKM = new QWidget;
                //WidgetKM=ui->tablePZ->cellWidget(itemR,0);
                //QLabel *YE=  QLabel(ui->tablePZ->cellWidget(itemR,0));
                //YE=ui->tablePZ->cellWidget(itemR,0)
                //KM->setText("123456");
                //qDebug()<< YE->text();
            }
            break;
            case 1:
                chkXM();
            break;
            case 2:
            {
                QRegExp rx(".*"); //摘要信息还是用无限制的好。 ^[\u4e00-\u9fa5]+$  代表只能输入中文
                QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                ui->txtInput->setValidator(pReg);
                ui->txtInput->setText(item->text());
                ui->txtInput->setVisible(true);
                ui->txtInput->selectAll();
                ui->txtInput->setFocus(Qt::OtherFocusReason);
                //拟加入获取余额的代码

                {
                    QString str="";
                    QString tmpStr=ui->tablePZ->item(itemR,0)->text();
                    if (tmpStr!=""){
                        str=tmpStr.left(tmpStr.indexOf("-"));
                    }
                    KMDM=str;
                    QString JDFX="";
                    int itemCount=0;
                    QTreeWidgetItemIterator it(ui->treeWidget);
                    while (*it) {
                        if  (KMDM==(*it)->text(0)){

                            JDFX=(*it)->text(5);

                            itemCount++;
                        }
                        ++it;
                    }
                    QString PZXM=ui->tablePZ->item(itemR,1)->text().trimmed();
                    QString HSXMTJ="";
                    if (PZXM!=""){
                        QStringList sl =PZXM.split(",");
                        QString returnstr="";
                        QString jstr="";
                            for (int i=0; i<sl.count(); i++){
                                if (sl[i]!=""){
                                    QStringList sl1 =sl[i].split(".");
                                    if (HSXMTJ!=""){
                                        HSXMTJ+=",";
                                    }
                                    HSXMTJ+=QString("%1").arg(sl1[0]);
                                }
                            }

                    }

                    QLabel *YE=new QLabel;
                    QFont font ( "Microsoft YaHei", 8, 50); //第一个属性是字体（微软雅黑），第二个是大小，第三个是加粗（权重是75）
                    YE->setFont(font);
                    double Jf=0;
                    double Df=0;
                    double Ye=0;
                    QSqlQuery r(mySQL::cn);
                    QString SQL="";

                    SQL="select jd,sum(je) as totje from pz ";
                    SQL+=QString(" where type_id='%1' ").arg(mySQL::TypeId);
                    SQL+=QString(" and kmdm='%1' ").arg(KMDM);
                    if (HSXMTJ!=""){
                        SQL+=QString(" and xmbh='%1' ").arg(HSXMTJ);
                    }

                    SQL+=QString(" group by jd ");
                    //qDebug()<<KMDM<<" "<<XMBH;
                    r.exec(SQL);
                    while(r.next()){
                        if (r.value("jd").toString().trimmed()=="借"){
                            Jf+=r.value("totje").toDouble();
                        }
                        if (r.value("jd").toString().trimmed()=="贷"){
                            Df+=r.value("totje").toDouble();
                        }
                    }
                    r.clear();

                    if (JDFX=="借方"){
                        Ye=Jf-Df;

                    }
                    if (JDFX=="贷方"){
                        Ye=Df-Jf;
                    }
                    YE->setText(QString("余额:%1").arg(Ye , 3, 'f', 2));
                    QWidget *WidgetKM = new QWidget;
                    QVBoxLayout* pLayout = new QVBoxLayout();//垂直布局
                    pLayout->addStretch();
                    pLayout->setMargin(0);  //控件与窗体左右边距
                    pLayout->addWidget(YE);

                    WidgetKM->setLayout(pLayout);
                    WidgetKM->resize(ui->tablePZ->columnWidth(0),lineHeight);
                    WidgetKM->setStyleSheet("QWidget{ border: 0px }");

                    YE->setStyleSheet("color:#9C9C9C;");
                    YE->move(0,0);
                    ui->tablePZ->removeCellWidget(itemR,0);
                    ui->tablePZ->setCellWidget(itemR,0,WidgetKM);
                }
            }
            break;
            case 3:
                {
                    QRegExp rx("^[ ]*$"); //借贷
                    QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                    ui->txtInput->setValidator(pReg);
                    ui->txtInput->setText(item->text());
                    ui->txtInput->setVisible(true);
                    ui->txtInput->selectAll();
                    ui->txtInput->setFocus(Qt::OtherFocusReason);
            }
            break;
            case 4:
            {
                QRegExp rx("^[ ]*$");//栏次
                QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                ui->txtInput->setValidator(pReg);
                ui->txtInput->setText(item->text());
                ui->txtInput->setVisible(true);
                ui->txtInput->selectAll();
                ui->txtInput->setFocus(Qt::OtherFocusReason);
            }
            break;
            case 5:
            {
                QRegExp rx("^(-?[0]|-?[1-9][0-9]{0,10})(?:\\.\\d{1,2})?$|(^\\t?$)");  //金额只允许输入2位小数 前面{0,10} 表示最大位数  后面的{1，2} 2位小数
                QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                ui->txtInput->setValidator(pReg);
                //QMessageBox::warning(this,"警告",ui->tablePZ->item(itemR,6)->text());
                if (ui->tablePZ->item(itemR,6)->text()!=""){
                    //USD-6.400 \n 888888
                    QString str=ui->tablePZ->item(itemR,6)->text();
                    QStringList sl =str.split("\n");
                    mySQL::SendString="正在读取外币内容";
                    ui->txtWB->setText(sl[1]);
                    QStringList sl1 =sl[0].split("-");
                    ui->cmbHB->setCurrentText(sl1[0]);
                    HSHB=sl1[0].trimmed();
                    ui->txtHL->setText(sl1[1]);
                    mySQL::SendString="";
                    ui->groupWB->move(x+ui->tablePZ->columnWidth(5),y);
                    ui->groupWB->setVisible(true);

                    //ui->txtWB->selectAll();
                }else{
                    HSHB="本币";
                    QTreeWidgetItemIterator it(ui->treeWidget);
                    QString tmpKM=ui->tablePZ->item(itemR,0)->text();
                    if(tmpKM!=""){
                        tmpKM=tmpKM.left(tmpKM.indexOf("-"));
                    }
                        while (*it) {
                             //(*it)->text(0);
                            if ((*it)->text(0)==tmpKM){
                                    HSHB=(*it)->text(4);
                            }
                            ++it;
                        }
                        if (HSHB!="本币"){
                            ui->cmbHB->setCurrentText(HSHB);
                            if (mySQL::SendString==""){
                                mySQL::SendString="输入凭证金额生成外汇金额！";
                                ui->txtWB->setText("0.00");
                                QString tmpje=ui->tablePZ->item(itemR,5)->text();
                                if (tmpje!="0.00"){
                                    double je=tmpje.toDouble();
                                    double hl=ui->txtHL->text().toDouble();
                                    ui->txtWB->setText(QString::number(je/hl, 'f', 2));
                                }
                                mySQL::SendString="";
                            }
                            ui->groupWB->move(x+ui->tablePZ->columnWidth(5),y);
                            ui->groupWB->setVisible(true);
                            //ui->txtWB->selectAll();
                            //ui->txtWB->setFocus(Qt::OtherFocusReason);
                        }
                }
                ui->txtInput->setText(item->text());
                ui->txtInput->setVisible(true);
                ui->txtInput->selectAll();
                ui->txtInput->setFocus(Qt::OtherFocusReason);
            }
            break;
            case 6:
            {



            }
            break;
            default:
            {
                QRegExp rx(".*");
                QRegExpValidator *pReg = new QRegExpValidator(rx, this);
                ui->txtInput->setValidator(pReg);
            }
            break;
        }
}


void FormPZLR::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{

    int i=column;
    i++;
    ui->txtInput->setText(item->text(0));
    ui->txtInput->setVisible(true);
    ui->txtInput->selectAll();
    ui->txtInput->setFocus(Qt::OtherFocusReason);

}

void FormPZLR::on_treeWidgetXM_itemClicked(QTreeWidgetItem *item, int column)
{
    QString sTmp=QString("%1,%2").arg(item->text(0)).arg(column);
    //这里判断勾选项目 打勾的自动处理
    QString str="";
    QString returnstr="";
    {
        QTreeWidgetItemIterator it(ui->treeWidgetXM);
        while (*it) {
            if ((*it)->checkState(0)==Qt::Checked){
                str+="";
                str+=(*it)->text(0);
                str+=",";
                returnstr+="";
                returnstr+=(*it)->text(0);
                returnstr+=".";
                returnstr+=(*it)->text(2);
                returnstr+=",";
            }
            ++it;
        }
        //returnstr=returnstr.left(returnstr.length()-1);
        //str=str.left(str.length()-1);
    }
    {
        QTreeWidgetItemIterator it(ui->treeWidgetXM);
            while (*it) {
                if ((*it)->childCount()==0){
                    (*it)->setCheckState (0, Qt::Unchecked);
                }
                ++it;
            }
    }
    QStringList sl =str.split(",");
        for (int i=0; i<sl.count(); i++){
            if (sl[i]!=""){
                QTreeWidgetItemIterator it(ui->treeWidgetXM);

                while (*it) {
                    QString tmpStr=(*it)->text(0);
                    if (tmpStr.left(1)==sl[i].left(1)){
                        if ((*it)->text(0)==sl[i]){
                            (*it)->setCheckState (0, Qt::Checked);
                        }else{
                            (*it)->setData(0, Qt::CheckStateRole, QVariant());
                        }
                    }
                    ++it;
                }
            }

        }
        ui->txtXMBH->setText(str);
        ui->txtXMMC->setText(returnstr);
        ui->tablePZ->item(itemR,1)->setText(returnstr);
}

void FormPZLR::on_btnCloseXM_clicked()
{
    ui->widgetXM->setVisible(false);
    on_tablePZ_itemClicked(ui->tablePZ->item(itemR, 2));
}

void FormPZLR::on_btnNEW_clicked()
{
    Start();
    //获取系统当前日期和最新凭证记账日期
}

/*****************************************************************/
//函数名称:MenuSlot
//函数参数:action
//函数返回值:NULL
//函数作用:根据行为判断当前所做的事
//备注:NULL
/*****************************************************************/
void FormPZLR::MenuSlot(QAction *action)
{
    int row = ui->tablePZ->rowCount();
    if(action == addRow)
    {  //插入一行
        ui->tablePZ->insertRow(row);
        ui->tablePZ->setItem(row,0,new QTableWidgetItem(""));
        ui->tablePZ->setItem(row,1,new QTableWidgetItem(""));
        ui->tablePZ->setItem(row,2,new QTableWidgetItem(ZYXX));
        ui->tablePZ->setItem(row,3,new QTableWidgetItem("借"));
        ui->tablePZ->setItem(row,4,new QTableWidgetItem(""));
        ui->tablePZ->setItem(row,5,new QTableWidgetItem("0.00"));
        ui->tablePZ->setItem(row,6,new QTableWidgetItem(""));
        ui->tablePZ->setItem(row,7,new QTableWidgetItem(""));
        ui->tablePZ->item(row,0)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(row,1)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(row,2)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        ui->tablePZ->item(row,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
        ui->tablePZ->item(row,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
        ui->tablePZ->item(row,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        ui->tablePZ->item(row,6)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        ui->tablePZ->scrollToBottom();  //滚动到底部
     }
    if (action == reRow) {//删除一行
        ui->tablePZ->removeRow(ui->tablePZ->currentRow());
    }
}

/*****************************************************************/
//作者:
//函数名称:showMenuPos
//函数作用:右键菜单显示位置
//备注:NULL
/*****************************************************************/
void FormPZLR::showMenuPos(QPoint)
{
    menu->exec(QCursor::pos());
}
void FormPZLR::on_cmbHB_currentTextChanged(const QString &arg1)
{
    QTreeWidgetItemIterator it(ui->treeWidgetWH);
    while (*it) {
            if ((*it)->text(2)==arg1){
                ui->txtHL->setText((*it)->text(3));
            }
        ++it;
    }
}

void FormPZLR::on_txtWB_textChanged(const QString &arg1)
{
    QString tmpje=ui->txtHL->text();
    if (mySQL::SendString==""){
        mySQL::SendString="输入外汇生成凭证金额！";
        if (arg1!="0.00"){
            double whje=arg1.toDouble();
            double hl=ui->txtHL->text().toDouble();
            double je=0;
            je=ui->tablePZ->item(itemR,5)->text().toDouble();

            if (je==0){
                ui->txtInput->setText(QString::number(whje*hl, 'f', 2));
                ui->tablePZ->item(itemR,5)->setText(QString::number(whje*hl, 'f', 2));
            }else{
                hl=je/whje;
                ui->txtHL->setText(QString::number(hl, 'f', 6));
            }

            QString str="";
            str+=ui->cmbHB->currentText();
            str+="-";
            str+=ui->txtHL->text();
            str+="\n";
            str+=ui->txtWB->text();
            ui->tablePZ->item(itemR,6)->setText(str);
        }
        mySQL::SendString="";
    }
}
void FormPZLR::on_btnSave_clicked()
{

    //这里写保存代码
    //先检查是否记账人自己， 再检查是否复核
    bool chkPZBJ=true;
    if (ui->txtPZBH->text()!=""){
        QString SQL="";
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        //先读取凭证总表
        SQL="select jzny,pzlx,jzrq,dj,jz,fhrq,fh from pzzb ";
        SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ui->cmbND->currentText()).arg(ui->txtPZBH->text());
        //qDebug()<<SQL;
        query.exec(SQL);
        while(query.next()){

            if (mySQL::UserName!=query.value("jz").toString().trimmed()){
                //非自己编辑的凭证禁止保存
                chkPZBJ=false;
                QMessageBox::warning(this,"警告","非原凭证记账人，不得修改！");
            }
            QString str=query.value("fh").toString().trimmed();
            if (str!=""){
                //已经复核的凭证禁止保存
                chkPZBJ=false;
                QMessageBox::warning(this,"警告","凭证已经复核入账，不得修改！");
            }
         }
    }
    if (chkPZBJ==true){
        if (RefJD()==true){
            QString tmpStr="凭证已通过！";
            //QMessageBox::warning(this,"警告",tmpStr);
            //检查成功后开始保存代码
            //先获取最大凭证编号
            QString SQL="";
            QString ND=ui->cmbND->currentText();
            int PZBH=0;

            QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
            if (ui->txtPZBH->text()==""){
                SQL="select max(pzbh) as t from pzzb ";
                SQL+=QString(" where type_id='%1' and nd='%2'  order by nd desc ").arg(mySQL::TypeId).arg(ND);
                query.exec(SQL);
                while(query.next()){
                    //QMessageBox::warning(this,"警告",query.value("t").toString());
                    PZBH=query.value("t").toInt();
                    //QMessageBox::warning(this,"警告",QString("最大凭证编号：%1").arg(PZBH));
                }
                PZBH++; //凭证编号+1 获取新的凭证号
            }else{
                PZBH=ui->txtPZBH->text().toInt();
            }

            QString JZNY="";
            JZNY+=ui->cmbND->currentText();
            JZNY+=ui->cmbYF->currentText();
            //保存凭证总表PZZB
            if (ui->txtPZBH->text()==""){
                SQL="INSERT INTO pzzb(type_id,nd,jzny,pzbh,pzlx,jzrq,dj,jz,fhrq,fh,xgrq) VALUES (";
                SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
                SQL+=QString("'%1',").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
                SQL+=QString("'%1',").arg(JZNY.trimmed().replace("'","''"));
                SQL+=QString("%1,").arg(PZBH);
                SQL+=QString("'%1',").arg(ui->cmbPZLX->currentText().trimmed().replace("'","''"));
                SQL+=QString("'%1',").arg(ui->dtPZRQ->text().trimmed().replace("'","''"));
                SQL+=QString("'%1',").arg(ui->txtDJ->text().trimmed().replace("'","''"));
                SQL+=QString("'%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
                SQL+="'2000-01-01',";
                SQL+="'',";
                SQL+=QString("'%1')").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
                //QMessageBox::warning(this,"警告",SQL);
                mySQL::cn.exec(SQL);
                ui->txtPZBH->setText(QString("%1").arg(PZBH));
            }else{
                SQL="update pzzb set ";//(type_id,nd,jzny,pzbh,pzlx,jzrq,dj,jz,fhrq,fh,xgrq) VALUES (";
                SQL+=QString("jzny='%1',").arg(JZNY.trimmed().replace("'","''"));
                SQL+=QString("pzlx='%1',").arg(ui->cmbPZLX->currentText().trimmed().replace("'","''"));
                SQL+=QString("jzrq='%1',").arg(ui->dtPZRQ->text().trimmed().replace("'","''"));
                SQL+=QString("dj='%1',").arg(ui->txtDJ->text().trimmed().replace("'","''"));
                SQL+=QString("jz='%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
                SQL+="fhrq='2000-01-01',";
                SQL+="fh='',";
                SQL+=QString("xgrq='%1' ").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
                SQL+=QString("where type_id='%1'").arg(mySQL::TypeId.trimmed().replace("'","''"));
                SQL+=QString(" and nd='%1'").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
                SQL+=QString(" and pzbh=%1").arg(PZBH);
                //QMessageBox::warning(this,"警告",SQL);
                //qDebug() << SQL;
                mySQL::cn.exec(SQL);
            }

            //删除就的凭证 先遍历找出所有有PZID的项目 为了删除非此凭证ID的项目
            SQL="delete from pz where ";
            SQL+=QString("type_id='%1' ").arg(mySQL::TypeId.trimmed().replace("'","''"));
            SQL+=QString("and nd='%1'").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
            SQL+=QString("and pzbh=%1 ").arg(PZBH);
            for(int i=0;i<ui->tablePZ->rowCount();i++){
                QString PZID=ui->tablePZ->item(i,7)->text();
                if (PZID!=""){
                    SQL+=QString("and (not pzid=%1) ").arg(PZID);
                }
            }
            mySQL::cn.exec(SQL);
            //开始保存凭证明细内容
            for(int i=0;i<ui->tablePZ->rowCount();i++){
                if(ui->tablePZ->item(i,0)!=NULL && ui->tablePZ->item(i,0)->text().trimmed()!="" ){
                    KMDM="";
                    XMBH="";
                    QString JD="";
                    QString LC="";
                    ZYXX="";
                    QString HB="CNY";
                    QString HL="1";
                    QString tmpStr="";
                    double JE=0;
                    double YB=0;//原币
                    KMDM=ui->tablePZ->item(i,0)->text();
                    if(KMDM!=""){
                        KMDM=KMDM.left(KMDM.indexOf("-"));
                    }
                    tmpStr=ui->tablePZ->item(i,1)->text();
                    if (tmpStr!=""){
                        QStringList sl =tmpStr.split(",");
                        QString returnstr="";
                        QString jstr="";
                            for (int i=0; i<sl.count(); i++){
                                QStringList sl1 =sl[i].split(".");
                                XMBH+=sl1[0]+",";
                            }
                        if (XMBH!=""){
                            XMBH=XMBH.left(XMBH.length()-1);
                        }
                    }
                    ZYXX=ui->tablePZ->item(i,2)->text();
                    JD=ui->tablePZ->item(i,3)->text();
                    LC=ui->tablePZ->item(i,4)->text();
                    JE=ui->tablePZ->item(i,5)->text().toDouble();
                    tmpStr=ui->tablePZ->item(i,6)->text();
                    if (tmpStr!=""){
                        QStringList sl =tmpStr.split("\n");
                        YB=sl[1].toDouble();
                        QStringList sl1 =sl[0].split("-");
                        HB=sl1[0];
                        HL=sl1[1];
                    }else{
                        YB=JE;
                        HB="CNY";
                        HL="1";
                    }
                    QString PZID=ui->tablePZ->item(i,7)->text();
                    if (PZID==""){
                        //凭证ID为空则insert into
                        SQL="INSERT INTO pz(type_id,nd,jzny,pzbh,pzlx,kmdm,xmbh,jd,lc,zyxx,je,yb,hb,hl,rq,jz) VALUES (";
                        SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(JZNY.trimmed().replace("'","''"));
                        SQL+=QString("%1,").arg(PZBH);
                        SQL+=QString("'%1',").arg(ui->cmbPZLX->currentText().trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(KMDM.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(XMBH.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(JD.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(LC.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ZYXX.trimmed().replace("'","''"));
                        SQL+=QString("%1,").arg(QString::number(JE, 'f', 2));
                        SQL+=QString("%1,").arg(QString::number(YB, 'f', 2));
                        SQL+=QString("'%1',").arg(HB.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(HL.trimmed().replace("'","''"));
                        SQL+=QString("'%1',").arg(ui->dtPZRQ->text().trimmed().replace("'","''"));
                        SQL+=QString("'%1')").arg(mySQL::UserName.trimmed().replace("'","''"));
                    }else{
                        //凭证ID不为空则update
                        SQL="update pz set "; //(type_id,nd,jzny,pzbh,pzlx,kmdm,xmbh,jd,lc,zyxx,je,yb,hb,hl,rq,jz) VALUES (";
                        SQL+=QString("type_id='%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
                        SQL+=QString("nd='%1',").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
                        SQL+=QString("jzny='%1',").arg(JZNY.trimmed().replace("'","''"));
                        SQL+=QString("pzbh=%1,").arg(PZBH);
                        SQL+=QString("pzlx='%1',").arg(ui->cmbPZLX->currentText().trimmed().replace("'","''"));
                        SQL+=QString("kmdm='%1',").arg(KMDM.trimmed().replace("'","''"));
                        SQL+=QString("xmbh='%1',").arg(XMBH.trimmed().replace("'","''"));
                        SQL+=QString("jd='%1',").arg(JD.trimmed().replace("'","''"));
                        SQL+=QString("lc='%1',").arg(LC.trimmed().replace("'","''"));
                        SQL+=QString("zyxx='%1',").arg(ZYXX.trimmed().replace("'","''"));
                        SQL+=QString("je=%1,").arg(QString::number(JE, 'f', 2));
                        SQL+=QString("yb=%1,").arg(QString::number(YB, 'f', 2));
                        SQL+=QString("hb='%1',").arg(HB.trimmed().replace("'","''"));
                        SQL+=QString("hl='%1',").arg(HL.trimmed().replace("'","''"));
                        SQL+=QString("rq='%1',").arg(ui->dtPZRQ->text().trimmed().replace("'","''"));
                        SQL+=QString("jz='%1' ").arg(mySQL::UserName.trimmed().replace("'","''"));
                        SQL+=QString(" where pzid=%1").arg(PZID.trimmed().replace("'","''"));
                    }
                    mySQL::cn.exec(SQL);
                    //QMessageBox::warning(this,"警告",SQL);
                }
            }
            int ZBID=0;
            SQL="select zbid from pzzb ";
            SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZBH);
            query.exec(SQL);
            while(query.next()){
                ZBID=query.value("zbid").toInt();
            }
            //保存之前检查一下电子发票内容是否已经保存
            int fpcount=0;
            {
                QTreeWidgetItemIterator it(ui->treeWidgetFP);
                while (*it) {
                     //(*it)->text(0);
                    if ((*it)->text(7).trimmed()=="新"){
                        fpcount++;
                    }
                    ++it;
                }
            }
            {
                if (fpcount>0){
                    QString tmpstr="";
                    tmpstr=QString("有%1条新增电子发票记录，是否需要保存？").arg(fpcount);
                    if (QMessageBox::information(NULL, "提醒", tmpstr,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
                        //开始保存发票信息
                        QTreeWidgetItemIterator it(ui->treeWidgetFP);
                        while (*it) {
                             //(*it)->text(0);
                            if ((*it)->text(7).trimmed()=="新"){
                                //<< "发票类型" << "发票代码" <<"发票号码" <<"金额（去税）" << "上传者" << "日期" << "原始信息" << "idd");
                                SQL="INSERT INTO invoice_info";
                                SQL+="(type_id,type,reidd,invoice_type,invoice_code,invoice_no,";
                                SQL+="invoice_date,amount,username,input_date,info) VALUES (";
                                SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
                                SQL+= "'记账凭证',";
                                SQL+=QString("'%1',").arg(ZBID);
                                SQL+=QString("'%1',").arg((*it)->text(0).trimmed().replace("'","''"));
                                SQL+=QString("'%1',").arg((*it)->text(1).trimmed().replace("'","''"));
                                SQL+=QString("'%1',").arg((*it)->text(2).trimmed().replace("'","''"));
                                QString FPRQ="";
                                QStringList FPinfo =(*it)->text(6).split(",");
                                FPRQ=FPinfo.at(5).left(4);
                                FPRQ+="-";
                                FPRQ+=FPinfo.at(5).mid(4,2);
                                FPRQ+="-";
                                FPRQ+=FPinfo.at(5).mid(6,2);
                                SQL+=QString("'%1',").arg(FPRQ.trimmed().replace("'","''"));
                                SQL+=QString("%1,").arg((*it)->text(3).trimmed().replace("'","''"));
                                SQL+=QString("'%1',").arg((*it)->text(4).trimmed().replace("'","''"));
                                SQL+=QString("'%1',").arg((*it)->text(5).trimmed().replace("'","''"));
                                SQL+=QString("'%1')").arg((*it)->text(6).trimmed().replace("'","''"));
                                //PZZBID
                                qDebug() <<SQL;
                                mySQL::cn.exec(SQL);
                            }
                            ++it;
                        }
                    }

                }
            }
            if (LoadPZ(ui->cmbND->currentText(),PZBH)==true){
                tmpStr="保存成功！";
                QMessageBox::information(this,"提示信息",tmpStr);
            }


        }else{
            QString tmpStr="凭证检查未通过！";
            tmpStr+="\n";
            tmpStr+=ui->labZT->text();
            QMessageBox::warning(this,"警告",tmpStr);
        }

    }




}
bool FormPZLR::LoadPZ(QString ND,int PZH){
    bool LoadFP=true;
    QString SQL="";
    QString str="";
    QString FHR="";
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    //先读取凭证总表
    SQL="select jzny,pzlx,jzrq,dj,jz,fhrq,fh from pzzb ";
    SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZH);
    //qDebug()<<SQL;
    query.exec(SQL);
    while(query.next()){
        ui->btnSave->setEnabled(true);
        if (mySQL::UserName!=query.value("jz").toString().trimmed()){
            //非自己编辑的凭证禁止保存
            ui->btnSave->setEnabled(false);
        }
        str=query.value("fh").toString().trimmed();
        if (str!=""){
            //已经复核的凭证禁止保存
            ui->btnSave->setEnabled(false);
        }
        //获取记账年月
        str=query.value("jzny").toString().trimmed();
        //qDebug()<<str;
        ui->cmbND->setCurrentText(str.left(4));
        ui->cmbYF->setCurrentText(str.mid(4,2));
        str=query.value("jzrq").toString().trimmed();
        QDate JZRQ=QDate::fromString(str, "yyyy-MM-dd");
        if (str.length()<10){
            JZRQ=QDate::fromString(str, "yyyy-M-d");
        }

        //qDebug()<<JZRQ;
        ui->dtPZRQ->setDate(JZRQ);
        str=query.value("dj").toString().trimmed();
        //qDebug()<<str;
        ui->txtDJ->setText(str);
        str=query.value("pzlx").toString().trimmed();
        //qDebug()<<str;
        ui->cmbPZLX->setCurrentText(str);
        //读取复核人信息 如果复核人为空则允许保存
        FHR=query.value("fh").toString().trimmed();
        ui->btnSave->setEnabled(true);
        if(FHR!=""){
            ui->btnSave->setEnabled(false);
        }

    }
    //type_id,nd,jzny,pzbh,pzlx,kmdm,xmbh,jd,lc,zyxx,je,yb,hb,hl,rq,jz
    SQL="select pzid,type_id,nd,jzny,pzbh,pzlx,kmdm,xmbh,jd,lc,zyxx,je,yb,hb,hl,rq,jz from pz ";
    SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZH);
    query.exec(SQL);
    int PZline=-1;
    while(query.next()){
        PZline++;
        if (PZline>=ui->tablePZ->rowCount()-1){
            int row = ui->tablePZ->rowCount();
                ui->tablePZ->insertRow(row);
                ui->tablePZ->setItem(row,0,new QTableWidgetItem(""));
                ui->tablePZ->setItem(row,1,new QTableWidgetItem(""));
                ui->tablePZ->setItem(row,2,new QTableWidgetItem(""));
                ui->tablePZ->setItem(row,3,new QTableWidgetItem("借"));
                ui->tablePZ->setItem(row,4,new QTableWidgetItem(""));
                ui->tablePZ->setItem(row,5,new QTableWidgetItem("0.00"));
                ui->tablePZ->setItem(row,6,new QTableWidgetItem(""));
                ui->tablePZ->setItem(row,7,new QTableWidgetItem(""));
                ui->tablePZ->item(row,0)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                ui->tablePZ->item(row,1)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                ui->tablePZ->item(row,2)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                ui->tablePZ->item(row,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                ui->tablePZ->item(row,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                ui->tablePZ->item(row,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                ui->tablePZ->item(row,6)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                ui->tablePZ->scrollToBottom();  //滚动到底部
        }
        str=query.value("pzid").toString().trimmed(); // 凭证ID
        ui->tablePZ->item(PZline,7)->setText(str);
        str=query.value("zyxx").toString().trimmed(); // 摘要信息
        ui->tablePZ->item(PZline,2)->setText(str);
        str=query.value("jd").toString().trimmed();//借贷
        ui->tablePZ->item(PZline,3)->setText(str);
        str=query.value("lc").toString().trimmed();// 栏次
        ui->tablePZ->item(PZline,4)->setText(str);
        str=QString::number(query.value("je").toDouble(), 'f', 2) ; // 金额
        ui->tablePZ->item(PZline,5)->setText(str);
        str=query.value("hb").toString().trimmed();// 货币
        str+="-";
        str+=query.value("hl").toString().trimmed();// 汇率
        str+="\n";
        str+=QString::number(query.value("yb").toDouble(), 'f', 2) ; // 原币 外汇
        if (query.value("hb").toString()=="CNY"){
            str="";
        }
        ui->tablePZ->item(PZline,6)->setText(str);
        str=query.value("xmbh").toString().trimmed();//项目编号
        ui->tablePZ->item(PZline,1)->setText(str); //项目编号

        str=query.value("kmdm").toString().trimmed();//科目代码

        QTreeWidgetItemIterator it(ui->treeWidget);
        QString fullKMMC="";//科目全称
        QString sKMMC="";//科目简称
        QString JDFX="";
        QString KMDM=query.value("kmdm").toString().trimmed();
        QString XMBH=query.value("xmbh").toString().trimmed();
        int itemCount=0;
        while (*it) {
            if  (str.left((*it)->text(0).length())==(*it)->text(0)){
                fullKMMC += "\\" +(*it)->text(1);
                sKMMC=(*it)->text(1);
                JDFX=(*it)->text(5);

                itemCount++;
            }
            ++it;
        }
        str+="-";
        str+=sKMMC;//fullKMMC;
        QLabel *KM=new QLabel;
        QLabel *YE=new QLabel;
        QFont font ( "Microsoft YaHei", 8, 50); //第一个属性是字体（微软雅黑），第二个是大小，第三个是加粗（权重是75）
        YE->setFont(font);
        KM->setText(str);
        //拟加入获取余额的代码

        {
            double Jf=0;
            double Df=0;
            double Ye=0;
            QSqlQuery r(mySQL::cn);
            SQL="select jd,sum(je) as totje from pz ";
            SQL+=QString(" where type_id='%1' ").arg(mySQL::TypeId);
            SQL+=QString(" and kmdm='%1' ").arg(KMDM);
            if (XMBH!=""){
                SQL+=QString(" and xmbh='%1' ").arg(XMBH);
            }

            SQL+=QString(" group by jd ");
            //qDebug()<<KMDM<<" "<<XMBH;
            r.exec(SQL);
            while(r.next()){
                if (r.value("jd").toString().trimmed()=="借"){
                    Jf+=r.value("totje").toDouble();
                }
                if (r.value("jd").toString().trimmed()=="贷"){
                    Df+=r.value("totje").toDouble();
                }
            }
            r.clear();

            if (JDFX=="借方"){
                Ye=Jf-Df;

            }
            if (JDFX=="贷方"){
                Ye=Df-Jf;
            }

            //str+=QString("\n余额:%1").arg(Ye , 3, 'f', 2);
            YE->setText(QString("余额:%1").arg(Ye , 3, 'f', 2));
            //str+=QString("\n\n余额:%1").arg(Ye , 3, 'f', 2));
        }
        ui->tablePZ->item(PZline,0)->setText(str); //科目代码

        QWidget *WidgetKM = new QWidget;
        QVBoxLayout* pLayout = new QVBoxLayout();//垂直布局
        pLayout->addStretch();
        //pLayout->addWidget(KM);
        //pLayout->addWidget(KM,0,0);
        //pLayout->addWidget(YE,0,0);
        pLayout->setMargin(0);  //控件与窗体左右边距
        pLayout->addWidget(YE);
        //KM->setStyleSheet ("background-color: rgb(255, 0, 0);");

        WidgetKM->setLayout(pLayout);
        WidgetKM->resize(ui->tablePZ->columnWidth(0),lineHeight);
        //WidgetKM->setStyleSheet("background-color: rgb(255, 255, 0);");
        WidgetKM->setStyleSheet("QWidget{ border: 0px }");
        //WidgetKM->move(0,lineHeight)
        //YE->resize(ui->tablePZ->columnWidth(0),lineHeight);
        //YE->setStyleSheet ("background-color: rgb(255, 255, 0);");
        YE->setStyleSheet("color:#9C9C9C;");
        YE->move(0,0);
        ui->tablePZ->setCellWidget(PZline,0,WidgetKM);


    }
    for(int i=0;i<ui->tablePZ->rowCount();i++){
        if(ui->tablePZ->item(i,0)!=NULL && ui->tablePZ->item(i,0)->text().trimmed()!="" ){
            str="";
            str=ui->tablePZ->item(i,1)->text().trimmed();
            if (str!=""){
                QString SS=" 1=2 ";
                QStringList sl =str.split(",");
                for (int j=0; j<sl.count(); j++)
                {
                    //qDebug() << sl.at(i);
                    SS+=QString(" or xmdm ='%1'").arg(sl.at(j));
                }
                SQL=QString("SELECT xmdm,xmmc,xmjc,xmzj FROM `hsxm` WHERE type_id='%1' and nd='%2' and (").arg(mySQL::TypeId).arg(ND)+ SS+ ") order by xmdm ";
                query.exec(SQL);
                str="";
                while(query.next()){
                    str+=query.value("xmdm").toString().trimmed();
                    str+=".";
                    str+=query.value("xmmc").toString().trimmed();
                    str+=",";
                }
                ui->tablePZ->item(i,1)->setText(str);
            }
        }
    }
    LoadFJ(ND,PZH); //读取附件
    return LoadFP;
}
void FormPZLR::on_btnLoad_clicked()
{
    // 获取整数
    //setWindowFlags(Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint);
    //this->setMinimumSize(200,200);
    QInputDialog* inputDialog=new  QInputDialog(this);
    inputDialog->setMinimumSize(220,200);
    bool ok;
    int  PZH=inputDialog->getInt(ui->tablePZ, tr("输入框"), tr("请输入凭证编号"), 1, 1, 99999, 1, &ok);
    //int  PZH= QInputDialog::getInt(this, tr("输入框"), tr("请输入凭证编号"), 1, 1, 9999999, 1, &ok);
    if(ok) {
        Start();
        if (LoadPZ(ui->cmbND->currentText(),PZH)==true){
            ui->txtPZBH->setText(QString("%1").arg(PZH));
            //QMessageBox::information(this,"提示信息","读取成功！");
        }else{
            QMessageBox::information(this,"提示信息","读取失败！");
        }
    }
}

void FormPZLR::on_btnPrint_clicked()
{
    //"|typeID|-|凭证年度|-|凭证月份|-|凭证类型|-|凭证编号|-|记账|-|记账日期|-|复核|-|复核日期|-|打印|-|打印日期|";
    QDateTime nowDateTime=QDateTime::currentDateTime();
    QString PZBH=ui->txtPZBH->text();
    QString JZ="";
    QString JZRQ="";
    QString FH="";
    QString FHRQ="";

    if (PZBH==""){
        QMessageBox::information(this,"提示信息","未保存的凭证无法打印！");
    }else{
        //先重新读取一遍保存号的凭证信息
        LoadPZ(ui->cmbND->currentText().trimmed(),PZBH.toInt());
        //先读取凭证总表
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        QString SQL="select jzny,pzlx,jzrq,dj,jz,fhrq,fh from pzzb ";
        SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ui->cmbND->currentText().trimmed()).arg(PZBH);
        query.exec(SQL);
        while(query.next()){
            JZ=query.value("jz").toString().trimmed();
            QString str=query.value("jzrq").toString().trimmed();
            JZRQ=QDate::fromString(str, "yyyy-MM-dd").toString("yyyy-MM-dd");

            FH=query.value("fh").toString().trimmed();
            if(FH!=""){
                 str=query.value("fhrq").toString().trimmed();
                 FHRQ=QDate::fromString(str, "yyyy-MM-dd").toString("yyyy-MM-dd");
            }
        }


        if (RefJD()==false){
            QMessageBox::information(this,"提示信息","接待不平衡！");
        }else{
            QString fileName="";
            fileName= QCoreApplication::applicationDirPath();
            fileName +="/tmp.pdf";
            QFile pdfFile(fileName);
            pdfFile.open(QIODevice::WriteOnly);                 // 打开要写入的pdf文件
            QPdfWriter* pPdfWriter = new QPdfWriter(&pdfFile);  // 创建pdf写入器
            pPdfWriter->setPageSize(QPagedPaintDevice::A5);     // 设置纸张为A5
            //QPdfWriter::setPageOrientation(QPageLayout::Orientation orientation)
            pPdfWriter->setPageOrientation(QPageLayout::Landscape); //Portrait 纵向打印  Landscape横向打印
            pPdfWriter->setResolution(300);                     // 设置纸张的分辨率为300,因此其像素为1754X2479
            pPdfWriter->setTitle("凭证输出");
            int iMargin = 60;                   // 页边距
            pPdfWriter->setPageMargins(QMarginsF(iMargin, iMargin/2, iMargin/2, iMargin/2)); //左右上下页边距
            QPainter* pPdfPainter = new QPainter(pPdfWriter);   // qt绘制工具

            // iTop 标题上边留白数字
            int iTop = 0;
            int lineheihgt=100; //行高
            int lineCount=0;
            //int PageNo=1;
            // 文本宽度 去除页边距后盛满
            int iContentWidth = pPdfWriter->width();
            int iContentheight = pPdfWriter->height();
            // 标题,居中
            QTextOption option(Qt::AlignHCenter | Qt::AlignVCenter);
            option.setWrapMode(QTextOption::WordWrap); //字段太长自动换行
            // 标题,24号字
            QFont font;
            font.setFamily("新宋体");
            int fontSize = 24;
            font.setPointSize(fontSize);
            pPdfPainter->setFont(font);                    // 为绘制工具设置字体
            QString str="";
            str="记账凭证";
            pPdfPainter->drawText(QRect(0, iTop, iContentWidth, 90),str, option); //打印标题
            //内容 10号字
            font.setFamily("新宋体");
            fontSize = 10;
            font.setPointSize(fontSize);
            pPdfPainter->setFont(font);
            option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
            option.setWrapMode(QTextOption::WordWrap);
            lineheihgt=50; //行高
            //iTop+=lineheihgt;
            str=ui->cmbPZLX->currentText()+QString(" 第 %1 号 ").arg(ui->txtPZBH->text());
            pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option); //内容
            iTop+=lineheihgt;
            str="记账日期："+ui->dtPZRQ->text();
            pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option);
            iTop+=lineheihgt;
            str=QString("附单据： %1 张").arg(ui->txtDJ->text());
            pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option);
            str=QString("使用单位：%1").arg(mySQL::SYDW);
            pPdfPainter->drawText(QRect(160, iTop, 1000, lineheihgt),str, option);
            // 设置画笔颜色
            pPdfPainter->setRenderHint(QPainter::Antialiasing, true);
            pPdfPainter->setPen(QPen(Qt::black, 2)); //设置颜色和粗细
            iTop+=lineheihgt;
            lineheihgt=140; //行高
            //绘制表格线
            pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线
            pPdfPainter->drawLine(QPointF(0, iTop), QPointF(0, iTop+lineheihgt) );//第1根竖线
            pPdfPainter->drawLine(QPointF(600, iTop), QPointF(600, iTop+lineheihgt) );//第2根竖线
            pPdfPainter->drawLine(QPointF(1200, iTop), QPointF(1200, iTop+lineheihgt) );//第3根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth-680, iTop), QPointF(iContentWidth-680, iTop+lineheihgt) );//第4根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth-340, iTop), QPointF(iContentWidth-340, iTop+lineheihgt) );//第5根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth, iTop), QPointF(iContentWidth, iTop+lineheihgt) );//最后一根竖线
            //绘制表头
            option.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            pPdfPainter->drawText(QRect(0, iTop, 600, lineheihgt),"摘要信息", option);
            pPdfPainter->drawText(QRect(600, iTop, 600, lineheihgt),"科目代码", option);
            pPdfPainter->drawText(QRect(1200, iTop, iContentWidth-680-1200, lineheihgt),"外币及汇率", option);
            pPdfPainter->drawText(QRect(iContentWidth-680, iTop, 340, lineheihgt),"借方", option);
            pPdfPainter->drawText(QRect(iContentWidth-340, iTop, 340, lineheihgt),"贷方", option);
            iTop+=lineheihgt;
            pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线
            fontSize = 8;  //内容字体缩小2号
            font.setPointSize(fontSize);
            pPdfPainter->setFont(font);

            double JF=0;
            double DF=0;
            int PageNo=1;
            for(int i=0;i<ui->tablePZ->rowCount();i++){
                if(ui->tablePZ->item(i,0)!=NULL && ui->tablePZ->item(i,0)->text().trimmed()!="" ){
                    lineCount++;
                    pPdfPainter->drawLine(QPointF(0, iTop), QPointF(0, iTop+lineheihgt) );//第1根竖线
                    pPdfPainter->drawLine(QPointF(600, iTop), QPointF(600, iTop+lineheihgt) );//第2根竖线
                    pPdfPainter->drawLine(QPointF(1200, iTop), QPointF(1200, iTop+lineheihgt) );//第3根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth-680, iTop), QPointF(iContentWidth-680, iTop+lineheihgt) );//第4根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth-340, iTop), QPointF(iContentWidth-340, iTop+lineheihgt) );//第5根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth, iTop), QPointF(iContentWidth, iTop+lineheihgt) );//最后一根竖线
                    //绘制内容 list1<<"科目代码"<<"部门/项目"<<"摘要信息"<<"借贷"<<"栏次"<<"金额"<<"外币"<<"PZID";
                    option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                    str=ui->tablePZ->item(i,2)->text().trimmed();  //摘要信息
                    pPdfPainter->drawText(QRect(0+2, iTop, 600-4, lineheihgt),str, option);
                    str=ui->tablePZ->item(i,0)->text().trimmed(); //科目代码
                    str+=" ";
                    str+=ui->tablePZ->item(i,1)->text().trimmed(); //项目代码
                    pPdfPainter->drawText(QRect(600+2, iTop, 600-4, lineheihgt),str, option);
                    option.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    str=ui->tablePZ->item(i,6)->text().trimmed();  //外币
                    pPdfPainter->drawText(QRect(1200+2, iTop, iContentWidth-680-1200-4, lineheihgt),str, option);
                    str=ui->tablePZ->item(i,3)->text().trimmed();
                    option.setAlignment(Qt::AlignRight | Qt::AlignVCenter);
                    if (str=="借") {
                        JF+=ui->tablePZ->item(i,5)->text().toDouble();
                        str = QString("%L1").arg(ui->tablePZ->item(i,5)->text().toDouble(), 3, 'f', 2);
                        pPdfPainter->drawText(QRect(iContentWidth-680+2, iTop, 340-4, lineheihgt),str, option);
                    }else{
                        DF+=ui->tablePZ->item(i,5)->text().toDouble();
                        str = QString("%L1").arg(ui->tablePZ->item(i,5)->text().toDouble(), 3, 'f', 2);
                        pPdfPainter->drawText(QRect(iContentWidth-340+2, iTop, 340-4, lineheihgt),str, option);
                    }
                    option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                    iTop+=lineheihgt;
                    pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线

                    //判断是否要另起一页
                    if (iTop+lineheihgt>iContentheight){
                        lineheihgt=30;
                        iTop+=2;
                        option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

                        str=QString("主管：%1").arg("");
                        pPdfPainter->drawText(QRect(0, iTop, iContentWidth/3, lineheihgt),str, option);
                        str=QString("复核：%1").arg("");
                        pPdfPainter->drawText(QRect(iContentWidth/3, iTop, iContentWidth*2/3, lineheihgt),str, option);
                        str=QString("记账：%1").arg(mySQL::UserName);
                        pPdfPainter->drawText(QRect(iContentWidth*2/3, iTop, iContentWidth, lineheihgt),str, option);
                        str= "第";
                        str+= QString("%1").arg(PageNo, 3);
                        str+=" 页";
                        PageNo++;
                        pPdfPainter->drawText(QRect(iContentWidth-200, iTop, iContentWidth, lineheihgt),str, option); //打印页脚+

                        str=QString("记账凭证,%1%2,").arg(ui->cmbND->currentText()).arg(ui->cmbYF->currentText());
                        str+=QString("%1,").arg(PZBH);
                        str+=QString("%1,").arg(ui->dtPZRQ->text());
                        str+=QString("%1,").arg(ui->labJD->text().replace("\n",",").replace("方","").replace(",差额：0.00",""));
                        str+=QString("%1,").arg(mySQL::UserName);
                        str+=QString("打印时间：%1,").arg(nowDateTime.toString("yyyy年MM月dd日hh时mm分ss秒"));
                        str=str.left(str.length()-1);
                        pPdfPainter->drawPixmap(0,0,145,145,JCode::QR_Pix(str,145,145));  //二维码打印

                        pPdfWriter->newPage();//开启新页
                        iTop=0;
                        //打印页头
                        // 标题,居中
                        QTextOption option(Qt::AlignHCenter | Qt::AlignVCenter);
                        option.setWrapMode(QTextOption::WordWrap); //字段太长自动换行
                        // 标题,24号字
                        QFont font;
                        font.setFamily("新宋体");
                        int fontSize = 24;
                        font.setPointSize(fontSize);
                        pPdfPainter->setFont(font);                    // 为绘制工具设置字体
                        str="记账凭证";
                        pPdfPainter->drawText(QRect(0, iTop, iContentWidth, 90),str, option); //打印标题
                        //内容 10号字
                        font.setFamily("新宋体");
                        fontSize = 10;
                        font.setPointSize(fontSize);
                        pPdfPainter->setFont(font);
                        option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                        option.setWrapMode(QTextOption::WordWrap);
                        lineheihgt=50; //行高
                        //iTop+=lineheihgt;
                        str=ui->cmbPZLX->currentText()+QString(" 第 %1 号 ").arg(ui->txtPZBH->text());
                        pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option); //内容
                        iTop+=lineheihgt;
                        str="记账日期："+ui->dtPZRQ->text();
                        pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option);
                        iTop+=lineheihgt;
                        str=QString("附单据： %1 张").arg(ui->txtDJ->text());
                        pPdfPainter->drawText(QRect(iContentWidth-500, iTop, iContentWidth, lineheihgt),str, option);
                        str=QString("使用单位：%1").arg(mySQL::SYDW);
                        pPdfPainter->drawText(QRect(160, iTop, 1000, lineheihgt),str, option);
                        // 设置画笔颜色
                        pPdfPainter->setRenderHint(QPainter::Antialiasing, true);
                        pPdfPainter->setPen(QPen(Qt::black, 2)); //设置颜色和粗细
                        iTop+=lineheihgt;
                        lineheihgt=140; //行高
                        //绘制表格线
                        pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线
                        pPdfPainter->drawLine(QPointF(0, iTop), QPointF(0, iTop+lineheihgt) );//第1根竖线
                        pPdfPainter->drawLine(QPointF(600, iTop), QPointF(600, iTop+lineheihgt) );//第2根竖线
                        pPdfPainter->drawLine(QPointF(1200, iTop), QPointF(1200, iTop+lineheihgt) );//第3根竖线
                        pPdfPainter->drawLine(QPointF(iContentWidth-680, iTop), QPointF(iContentWidth-680, iTop+lineheihgt) );//第4根竖线
                        pPdfPainter->drawLine(QPointF(iContentWidth-340, iTop), QPointF(iContentWidth-340, iTop+lineheihgt) );//第5根竖线
                        pPdfPainter->drawLine(QPointF(iContentWidth, iTop), QPointF(iContentWidth, iTop+lineheihgt) );//最后一根竖线
                        //绘制表头
                        option.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                        pPdfPainter->drawText(QRect(0, iTop, 600, lineheihgt),"摘要信息", option);
                        pPdfPainter->drawText(QRect(600, iTop, 600, lineheihgt),"科目代码", option);
                        pPdfPainter->drawText(QRect(1200, iTop, iContentWidth-680-1200, lineheihgt),"外币及汇率", option);
                        pPdfPainter->drawText(QRect(iContentWidth-680, iTop, 340, lineheihgt),"借方", option);
                        pPdfPainter->drawText(QRect(iContentWidth-340, iTop, 340, lineheihgt),"贷方", option);
                        iTop+=lineheihgt;
                        pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线
                        fontSize = 8;  //内容字体缩小2号
                        font.setPointSize(fontSize);
                        pPdfPainter->setFont(font);
                    }
                }

            }
            //合计
            lineCount++;
            pPdfPainter->drawLine(QPointF(0, iTop), QPointF(0, iTop+lineheihgt) );//第1根竖线
            pPdfPainter->drawLine(QPointF(600, iTop), QPointF(600, iTop+lineheihgt) );//第2根竖线
            pPdfPainter->drawLine(QPointF(1200, iTop), QPointF(1200, iTop+lineheihgt) );//第3根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth-680, iTop), QPointF(iContentWidth-680, iTop+lineheihgt) );//第4根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth-340, iTop), QPointF(iContentWidth-340, iTop+lineheihgt) );//第5根竖线
            pPdfPainter->drawLine(QPointF(iContentWidth, iTop), QPointF(iContentWidth, iTop+lineheihgt) );//最后一根竖线
            option.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            pPdfPainter->drawText(QRect(0, iTop, 600, lineheihgt),"*********", option);
            pPdfPainter->drawText(QRect(600, iTop, 600, lineheihgt),"*********", option);
            pPdfPainter->drawText(QRect(1200, iTop, iContentWidth-680-1200, lineheihgt),"合计：", option);
            option.setAlignment(Qt::AlignRight | Qt::AlignVCenter);
            str = QString("%L1").arg(JF, 3, 'f', 2);
            pPdfPainter->drawText(QRect(iContentWidth-680, iTop, 340, lineheihgt),str, option);
            str = QString("%L1").arg(DF, 3, 'f', 2);
            pPdfPainter->drawText(QRect(iContentWidth-340, iTop, 340, lineheihgt),str, option);
            option.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            iTop+=lineheihgt;
            pPdfPainter->drawLine(QPointF(0, iTop), QPointF(iContentWidth, iTop) ); //表格横线
            //自动填充空行
                while (iTop+lineheihgt<iContentheight)
                {
                    pPdfPainter->drawLine(QPointF(0, iTop), QPointF(0, iTop+lineheihgt) );//第1根竖线
                    pPdfPainter->drawLine(QPointF(600, iTop), QPointF(600, iTop+lineheihgt) );//第2根竖线
                    pPdfPainter->drawLine(QPointF(1200, iTop), QPointF(1200, iTop+lineheihgt) );//第3根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth-680, iTop), QPointF(iContentWidth-680, iTop+lineheihgt) );//第4根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth-340, iTop), QPointF(iContentWidth-340, iTop+lineheihgt) );//第5根竖线
                    pPdfPainter->drawLine(QPointF(iContentWidth, iTop), QPointF(iContentWidth, iTop+lineheihgt) );//最后一根竖线
                    iTop+=lineheihgt;
                    pPdfPainter->drawLine(QPointF(0, iTop), QPointF(pPdfWriter->width(), iTop) ); //表格横线
                }
                //iTop-=lineheihgt;
            lineheihgt=30;
            iTop+=2;

            option.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
            str=QString("主管：%1").arg("");
            pPdfPainter->drawText(QRect(0, iTop, iContentWidth/3, lineheihgt),str, option);
            str=QString("复核：%1").arg(FH);
            pPdfPainter->drawText(QRect(iContentWidth/3, iTop, iContentWidth*2/3, lineheihgt),str, option);

            str=QString("记账：%1").arg(JZ);
            pPdfPainter->drawText(QRect(iContentWidth*2/3, iTop, iContentWidth, lineheihgt),str, option);
            str= "第";
            str+= QString("%1").arg(PageNo, 3);
            str+=" 页";
            PageNo++;
            pPdfPainter->drawText(QRect(iContentWidth-200, iTop, iContentWidth, lineheihgt),str, option); //打印页脚+

/*
            str=QString("记账凭证,%1%2,").arg(ui->cmbND->currentText()).arg(ui->cmbYF->currentText());
            str+=QString("%1,").arg(PZBH);
            str+=QString("%1,").arg(ui->dtPZRQ->text());
            str+=QString("%1,").arg(ui->labJD->text().replace("\n",",").replace("方","").replace(",差额：0.00",""));
            str+=QString("%1,").arg(mySQL::UserName);
            str+=QString("打印时间：%1,").arg(nowDateTime.toString("yyyy年MM月dd日hh时mm分ss秒"));
            str=str.left(str.length()-1);
            */
            //"|typeID|-|凭证年度|-|凭证月份|-|凭证类型|-|凭证编号|-|记账|-|记账日期|-|复核|-|复核日期|-|打印|-|打印日期|";
            QString QRstr=QString("%1").arg(mySQL::PZQR);
            if (QRstr!=""){
                //读取二维码信息，如果不为空打印二维码
                //QMessageBox::warning(this,"警告",QRstr);
                QRstr=QRstr.replace("|typeID|",mySQL::TypeId);
                QRstr=QRstr.replace("|凭证年度|",ui->cmbND->currentText());
                QRstr=QRstr.replace("|凭证月份|",ui->cmbYF->currentText());
                QRstr=QRstr.replace("|凭证类型|",ui->cmbPZLX->currentText());
                QRstr=QRstr.replace("|凭证编号|",ui->txtPZBH->text());
                QRstr=QRstr.replace("|记账|",JZ);
                QRstr=QRstr.replace("|记账日期|",JZRQ);
                QRstr=QRstr.replace("|复核|",FH);
                QRstr=QRstr.replace("|复核日期|",FHRQ);
                QRstr=QRstr.replace("|打印|",mySQL::UserName);
                QRstr=QRstr.replace("|打印日期|",QDate::currentDate().toString("yyyy-MM-dd"));
                QRstr=QRstr.replace("-",",");
                //QMessageBox::warning(this,"警告",QRstr);
                pPdfPainter->drawPixmap(0,0,145,145,JCode::QR_Pix(QRstr,145,145));  //二维码打印
            }


            pPdfPainter->setPen(QColor(0, 0, 0));
            delete pPdfPainter;
            delete pPdfWriter;
            pdfFile.close();
            //QMessageBox::warning(this,"警告",fileName);
            QDesktopServices::openUrl(QUrl::fromLocalFile(fileName)); //根据你电脑默认的PDF打开方式 直接打开PDF文件 需要安装阅读器
        }

    }



}

void FormPZLR::on_txtHL_textChanged(const QString &arg1)
{

    if (mySQL::SendString=="" && ui->tablePZ->item(itemR,6)->text()!="" ){
        mySQL::SendString="修改汇率生成凭证金额！";


        if ( arg1!=""){
            double hl=0;
            hl=arg1.toDouble();


            if (hl!=0){
                QString str=ui->txtWB->text();
                //QMessageBox::warning(this,"警告",QString::number(itemR, 'f', 2));

                if (str!=""){
                    double whje=str.toDouble();
                    double je=0;
                    je=whje*hl;
                    ui->txtInput->setText(QString::number(je, 'f', 2));
                    ui->tablePZ->item(itemR,5)->setText(QString::number(je, 'f', 2));
                }else{
                        str=ui->tablePZ->item(itemR,5)->text();
                        double je=0;
                        je=str.toDouble();
                        double wb=0;
                        wb=je/hl;
                        ui->txtWB->setText(QString::number(wb, 'f', 2));
                }

                str+=ui->cmbHB->currentText();
                str+="-";
                str+=ui->txtHL->text();
                str+="\n";
                str+=ui->txtWB->text();
                ui->tablePZ->item(itemR,6)->setText(str);

            }

        }

        mySQL::SendString="";
    }

}

void FormPZLR::on_btnPaste_clicked()
{
    QMessageBox message(QMessageBox::Warning,"请确认","确认粘贴数据的格式为 \n[科目代码]，[项目代码]，[摘要信息]，[借贷]，[金额]，[货币]，[汇率]，[原币金额]?",QMessageBox::Yes|QMessageBox::No,NULL);
        if (message.exec()==QMessageBox::Yes)
        {
            QClipboard *board = QApplication::clipboard();
            QString tmpstr = board->text();
            //QMessageBox::information(NULL, "From clipboard", str);
            QStringList strList = tmpstr.split("\n");
            int PZline=-1;
            for(int i = 0; i < strList.size()-1; i++) {
                QStringList subList = strList[i].split("\t");
                {

                    PZline++;
                        if (PZline>=ui->tablePZ->rowCount()-1){
                            int row = ui->tablePZ->rowCount();
                                ui->tablePZ->insertRow(row);
                                ui->tablePZ->setItem(row,0,new QTableWidgetItem(""));
                                ui->tablePZ->setItem(row,1,new QTableWidgetItem(""));
                                ui->tablePZ->setItem(row,2,new QTableWidgetItem(""));
                                ui->tablePZ->setItem(row,3,new QTableWidgetItem("借"));
                                ui->tablePZ->setItem(row,4,new QTableWidgetItem(""));
                                ui->tablePZ->setItem(row,5,new QTableWidgetItem("0.00"));
                                ui->tablePZ->setItem(row,6,new QTableWidgetItem(""));
                                ui->tablePZ->setItem(row,7,new QTableWidgetItem(""));
                                ui->tablePZ->item(row,0)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                ui->tablePZ->item(row,1)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                ui->tablePZ->item(row,2)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                                ui->tablePZ->item(row,3)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                ui->tablePZ->item(row,4)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                ui->tablePZ->item(row,5)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                                ui->tablePZ->item(row,6)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
                                ui->tablePZ->scrollToBottom();  //滚动到底部
                        }
                        //[科目代码]，[项目代码]，[摘要信息]，[借贷]，[金额]，[货币]，[汇率]，[金额]
                        QString str="";
                        str=""; // 凭证ID
                        ui->tablePZ->item(PZline,7)->setText(str);
                        str=subList[2].trimmed(); // 摘要信息
                        ui->tablePZ->item(PZline,2)->setText(str);
                        str=subList[3].trimmed();//借贷
                        ui->tablePZ->item(PZline,3)->setText(str);
                        str="";// 栏次
                        ui->tablePZ->item(PZline,4)->setText(str);
                        str=QString::number(subList[4].toDouble(), 'f', 2) ; // 金额
                        ui->tablePZ->item(PZline,5)->setText(str);
                        str=subList[5].trimmed();// 外币
                        str+="-";
                        str+=subList[6].trimmed();// 汇率
                        str+="\n";
                        str+=QString::number(subList[7].toDouble(), 'f', 2) ; // 原币 外汇
                        if (subList[5].trimmed()=="CNY"){
                            str="";
                        }
                        ui->tablePZ->item(PZline,6)->setText(str);
                        str=subList[0].trimmed();//科目代码
                        QTreeWidgetItemIterator it(ui->treeWidget);
                        QString fullKMMC="";//科目全称
                        int itemCount=0;
                        while (*it) {
                            if  (str.left((*it)->text(0).length())==(*it)->text(0)){
                                fullKMMC += "\\" +(*it)->text(1);
                                itemCount++;
                            }
                            ++it;
                        }
                        str+="-";
                        str+=fullKMMC;
                        ui->tablePZ->item(PZline,0)->setText(str); //科目代码
                        str=subList[1].trimmed();//项目编号
                        ui->tablePZ->item(PZline,1)->setText(str); //项目编号

                    }
            }
        }
}

void FormPZLR::on_btnCopy_clicked()
{
    int rows=ui->tablePZ->rowCount();
    int column=ui->tablePZ->columnCount();
    QString str="";
    for(int i=0; i<rows; i++) // 取出每个格子的内容
    {
        for(int j=0; j<column; j++){
            if(ui->tablePZ->item(i,j) != NULL){//一定要先判断非空，否则会报错
                str.append(ui->tablePZ->item(i,j)->text());
                str.append("\t");
            }else{
                str.append(""); //空字符弄成空格
                str.append("\t");
            }
        }
        str.append("\n");
    }
    QClipboard *board = QApplication::clipboard();
    board->setText(str);
    QMessageBox::information(NULL, "信息", "复制成功！");
}


void FormPZLR::on_btnPZFJ_clicked()
{
    bool LoadFP=false;
    if (ui->txtPZBH->text()!=""){ //凭证编号不得未空
        //判断凭证编号是否有效

        QString SQL="";
        QString ND=ui->cmbND->currentText();
        QString PZH=ui->txtPZBH->text();
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        //先读取凭证总表
        SQL="select jzny,pzlx,jzrq,dj,jz,fhrq,fh from pzzb ";
        SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZH);
        query.exec(SQL);
        while(query.next()){
            LoadFP=true;
        }
        mySQL::SendString=QString("%1").arg(PZH);

    }
    if (LoadFP==true){

        FormPZ_FJ * formPZFJ =new class FormPZ_FJ;
        formPZFJ->show();
    }else{
        mySQL::SendString="";
        QMessageBox::information(NULL, "信息", "无效的凭证编号！");
    }
}

void FormPZLR::on_btnInvoice_clicked()
{
    FormPZ_FPCY * formPZFPCY =new class FormPZ_FPCY;
    formPZFPCY->show();
    formPZFPCY->setWindowTitle("发票查验系统");
    connect(formPZFPCY,SIGNAL(sendData(QString)),this,SLOT(receiveDZFP(QString)));
}
void FormPZLR::receiveDZFP(QString DATA){
    //QMessageBox::information(NULL, "信息", DATA);
    int DJ=0;
    QStringList FP =DATA.split("\n");
    for (int i=0; i<FP.count(); i++){
        if (FP.at(i)!=""){
            QStringList FPinfo =FP.at(i).split(",");
            QStringList child;
            for (int j=0; j<ui->cmbFPLX->count(); j++){
                if (ui->cmbFPLX->itemText(j).left(2)==FPinfo.at(1).right(2)){
                    ui->cmbFPLX->setCurrentIndex(j);
                }
            }
            child << ui->cmbFPLX->currentText();
            child << FPinfo.at(2).trimmed();
            child << FPinfo.at(3).trimmed();
            child << FPinfo.at(4).trimmed();
            child << mySQL::UserName.trimmed();
            child << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
            child << FP.at(i) ;
            child << "新";
            bool f=false; //寻找列表中是否有以及导入的发票信息
            QTreeWidgetItemIterator it(ui->treeWidgetFP);
            while (*it) {
                 //(*it)->text(0);
                if ((*it)->text(1)==FPinfo.at(2).trimmed() && (*it)->text(2)==FPinfo.at(3).trimmed()){
                    f=true;
                }
                ++it;
            }
            if  (f==false){
                QTreeWidgetItem * citem =new QTreeWidgetItem(child);
                citem->setCheckState(0, Qt::Unchecked);
                ui->treeWidgetFP->addTopLevelItem(citem);
                DJ++;
            }
        }
    }    
    QMessageBox::information(NULL, "信息", QString("导入了%1条电子发票信息！").arg(DJ));
    DJ+=ui->txtDJ->text().toInt();
    ui->txtDJ->setText(QString("%1").arg(DJ));
}

void FormPZLR::LoadFJ(QString ND,int PZBH){
    //保存到数据库里面
    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
    //先读取凭证总表 获取ZBID
    QString SQL="";
    int ZBID=0;
    SQL="select zbid from pzzb ";
    SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ND).arg(PZBH);
    query.exec(SQL);
    while(query.next()){
        ZBID=query.value("zbid").toInt();
    }
    ui->treeWidgetFJ->clear();
    ui->treeWidgetFJ->setHeaderLabels(QStringList() << "文件名"  << "上传者" << "上传日期" <<"idd" );
    ui->treeWidgetFJ->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度

    if (ZBID!=0){
        SQL="SELECT idd,type_id,type,type_idd,username,upload_date,filename FROM upfiles ";
        SQL+=QString(" where type_id='%1' and type_idd='%2' and type='凭证附件' ORDER BY upload_date ").arg(mySQL::TypeId).arg(ZBID);
        query.exec(SQL);
        while(query.next()){
            QStringList child;
            child<<query.value("filename").toString().trimmed();
            child<<query.value("username").toString().trimmed();
            child<<query.value("upload_date").toDateTime().toString("yyyy-MM-dd hh:mm:ss");
            child<<query.value("idd").toString().trimmed();
            QTreeWidgetItem * citem =new QTreeWidgetItem(child);
            citem->setCheckState(0, Qt::Unchecked);
            citem->setSelected(false);
            ui->treeWidgetFJ->addTopLevelItem(citem);
        }
        //检查发票信息
        ui->treeWidgetFP->clear();
        //ui->treeWidgetFP->setStyleSheet( "QTreeView::item:hover{background-color:rgb(0,255,0,50)}"
        //                                 "QTreeView::item:selected{background-color:rgb(255,0,0,100)}" );
        ui->treeWidgetFP->setHeaderLabels(QStringList() << "发票类型" << "发票代码" <<"发票号码" <<"金额（去税）" << "上传者" << "日期" << "原始信息" << "idd");
        ui->treeWidgetFP->header()->setSectionResizeMode(QHeaderView::ResizeToContents); //QTreeWidget设置根据内容自适应宽度
        SQL="select idd,invoice_type,invoice_code,invoice_no,invoice_date,amount,info,username,input_date,info from invoice_info ";
        SQL+=QString(" where type_id='%1' and reidd='%2' and type='记账凭证' ORDER BY input_date ").arg(mySQL::TypeId).arg(ZBID);

        //SQL+=QString(" where type_id='%1' and invoice_code='%2' and invoice_no='%3'  ").arg(mySQL::TypeId).arg(ui->txtFPDM->text()).arg(ui->txtFPH->text());

        query.exec(SQL);
        while(query.next()){

            QStringList child;
            child<<query.value("invoice_type").toString().trimmed();
            child<<query.value("invoice_code").toString().trimmed();
            child<<query.value("invoice_no").toString().trimmed();
            child<<QString::number(query.value("amount").toDouble(),'f',2);
            child<<query.value("username").toString().trimmed();
            child<<query.value("input_date").toDateTime().toString("yyyy-MM-dd hh:mm:ss");
            child<<query.value("info").toString().trimmed();
            child<<query.value("idd").toString().trimmed();
            QTreeWidgetItem * citem =new QTreeWidgetItem(child);
            citem->setSelected(false);
            citem->setCheckState(0, Qt::Unchecked);
            ui->treeWidgetFP->addTopLevelItem(citem);
        }
    }
}

void FormPZLR::on_treeWidgetFJ_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int i=column;
    i++;
    i--;
    QString url=QString("http://%1/up_file/uploadFinancial/%2/%3").arg(mySQL::ServerWEB).arg(item->text(1)).arg(item->text(0));
    QString Localfile=QString("%1/pdftmp/%2").arg(QDir::currentPath()).arg(item->text(0));
    if (ui->optSaveAS->isChecked()==true){
        QFileDialog fileDialog;
        QString str = fileDialog.getSaveFileName(this,tr("附件另存为"),item->text(0),tr("所有文件 (*.*)"));
        if(str == "")
        {
            return;
        }
        Localfile=str;
    }
    //QMessageBox::information(NULL, "文件名", url);
    //QMessageBox::information(NULL, "文件名", Localfile);
    if (DownLoadFile(url,Localfile)==true){
        if (ui->optOpen->isChecked()==true){
           QDesktopServices::openUrl(QUrl::fromLocalFile(Localfile));
        }

    }
}

void FormPZLR::on_btnCamera_clicked()
{
    int PZH=0;
    PZH=ui->txtPZBH->text().toInt();
    if (PZH==0){
        QMessageBox::information(this, "提示信息", "请先保存凭证！");
        return;
    }
    FormCam * formCAM =new class FormCam;
    formCAM->show();
    connect(formCAM,SIGNAL(sendData(QString)),this,SLOT(receiveCAM(QString)));
}
void FormPZLR::receiveCAM(QString data){
    //QMessageBox::information(NULL, "信息", data);
    QDateTime curDateTime=QDateTime::currentDateTime();
    QFile file1(data);
    QDir *folder = new QDir;
    QString aFile = QDir::currentPath();

    QString pdfPath =QString("%1/pdftmp").arg(aFile);
    folder->mkdir(pdfPath);
    QString FileName=QString("pz_%1.pdf").arg(curDateTime.toString("yyyyMMdd-hhmmss"));
    pdfPath+=QString("/%1").arg(FileName);
    file1.copy(pdfPath);
    QString url=QString("http://%1/up_file/upfileCW.php").arg(mySQL::ServerWEB);
    //QSting 转换一下
    QByteArray ba2;
    ba2.append(mySQL::UserName);     //也可以 ba2 = s2.toLatin1();
    const char* SN=ba2.data();
    FileUPload(url,pdfPath,SN);
}
bool FormPZLR::DownLoadFile(QString FileUrl,QString LocalFile)
{
   QUrl url(FileUrl);
   QNetworkAccessManager manager;
   QEventLoop loop;
   // qDebug() << "图片下载地址： " << GifUrl;
   QNetworkReply *reply = manager.get(QNetworkRequest(url));
   //请求结束并下载完成后，退出子事件循环
   QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
   //开启子事件循环
   loop.exec();
   QByteArray Filemsg = reply->readAll();

       QFile file(LocalFile);
       if(!file.open(QFile::WriteOnly))
       {
           qDebug() << "open file fail";
           exit(1);
       }
       file.write(Filemsg);
       file.close();
       return true;

}
void FormPZLR::FileUPload(QString url,QString FileName,const char * SN)
{
        QString uploadFilename=FileName;//上传路径,可自定义
        //QMessageBox::information(NULL, "信息", uploadFilename);
        QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

        QHttpPart imagePart;
        QFile *file = new QFile(uploadFilename);
        file->open(QIODevice::ReadOnly);
        imagePart.setBodyDevice(file);
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html"));//设置上传文件类型
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"" + file->fileName() + "\""));
        multiPart->append(imagePart);

        QHttpPart dataPart;
        //在body体中设置值，
        dataPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"sn\""));
        dataPart.setBody(SN);
        multiPart->append(dataPart);

        QUrl Qurl(url);
        QNetworkRequest request(Qurl);

        QNetworkAccessManager *networkManager= new QNetworkAccessManager;
        reply = networkManager->post(request, multiPart);
        multiPart->setParent(reply);
        //关联槽,上传完成后输出返回信息
        connect(reply,SIGNAL(finished()),this,SLOT(uploadFinished()));

}
void FormPZLR::uploadFinished()
{
    // 获取数据
    if (QNetworkReply::NoError == reply->error()){
        int PZH=0;
        PZH=ui->txtPZBH->text().toUInt();
        QByteArray context = reply->readAll();
        //QTextCodec* pCodec = QTextCodec::codecForName("UTF-8");
        //QString strResult = pCodec->toUnicode(context);//输出返回的文本

        QJsonObject result_obj = QJsonDocument::fromJson(context).object();
        QString Filename = result_obj.value("filename").toString();
        qDebug()<<"filename:"<<Filename<<result_obj;
        QString str=QString("文件上传成功！！\n文件名:%1").arg(Filename);
        QMessageBox::information(NULL, "信息", str);
        //保存到数据库里面
        QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
        //先读取凭证总表
        QString SQL="";
        int ZBID=0;
        SQL="select zbid from pzzb ";
        SQL+=QString(" where type_id='%1' and nd='%2' and pzbh=%3 ").arg(mySQL::TypeId).arg(ui->cmbND->currentText()).arg(PZH);
        query.exec(SQL);
        while(query.next()){
            ZBID=query.value("zbid").toInt();
        }
        //str=QString("ZBID=%1").arg(ZBID);
        //QMessageBox::information(NULL, "信息", str);
        if(ZBID>0){
            QDateTime curDateTime=QDateTime::currentDateTime();
            //QString FileName=QString("pz_%1.pdf").arg(curDateTime.toString("yyyyMMdd-hhmmss"));
            SQL="INSERT INTO upfiles(type_id,type,type_idd,username,upload_date,filename) VALUES (";
            SQL+=QString("'%1',").arg(mySQL::TypeId.trimmed().replace("'","''"));
            SQL+=QString("'%1',").arg("凭证附件");
            SQL+=QString("'%1',").arg(ZBID);
            SQL+=QString("'%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
            SQL+=QString("'%1',").arg(curDateTime.toString("yyyy-MM-dd hh:mm:ss"));
            SQL+=QString("'%1')").arg(Filename);
            str=QString("SQL=%1").arg(SQL);
            //qDebug()<<SQL;
            //QMessageBox::information(NULL, "信息", str);
            query.exec(SQL);
            LoadFJ(ui->cmbND->currentText(),PZH); //保存成功后刷新附件列表
        }
    }
    else{
        //qDebug()<<"error string:"<<reply->errorString();
        QString str=QString("文件上传失败！！\n错误信息:%1").arg(reply->errorString());
        QMessageBox::information(NULL, "信息", str);
        reply->deleteLater();
    }
}


void FormPZLR::on_btnFile_clicked()
{
    //打开图片操作
       QString fileName = QFileDialog::getOpenFileName(
                   this, tr("选择图片"),
                   "./",tr("PDF files(*.pdf);;Image files(*.bmp *.jpg *.png );;All file *.* ;"));
       if(fileName.isEmpty())
       {
            QMessageBox mesg;
            mesg.warning(this,"警告","打开图片失败！");
            return;
       }
       else
       {
           QMessageBox::information(NULL, "信息", fileName);
           QFileInfo appInfo(fileName);
           //QMessageBox::information(NULL, "文件名", appInfo.baseName());
           //QMessageBox::information(NULL, "//扩展名", appInfo.suffix());
           QString fileType=appInfo.suffix();
           QDateTime curDateTime=QDateTime::currentDateTime();
           QFile file1(fileName);
           QDir *folder = new QDir;
           QString aFile = QDir::currentPath();

           QString pdfPath =QString("%1/pdftmp").arg(aFile);
           folder->mkdir(pdfPath);
           QString FileName=QString("pz_%1.%2").arg(curDateTime.toString("yyyyMMdd-hhmmss")).arg(fileType);
           pdfPath+=QString("/%1").arg(FileName);
           file1.copy(pdfPath);
           QString url=QString("http://%1/up_file/upfileCW.php").arg(mySQL::ServerWEB);
           //QSting 转换一下
           QByteArray ba2;
           ba2.append(mySQL::UserName);     //也可以 ba2 = s2.toLatin1();
           const char* SN=ba2.data();
           FileUPload(url,pdfPath,SN);

       }

}
void FormPZLR::GetHTTP(QString Url){
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    QNetworkRequest request;
    request.setUrl(QUrl(Url));
    Httpreply = manager->get(request);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinish(QNetworkReply*)));
}
void FormPZLR::replyFinish(QNetworkReply* reply)
{
    qDebug()<<reply->readAll();
}
void FormPZLR::on_btnDelFile_clicked()
{
    QTreeWidgetItemIterator it(ui->treeWidgetFJ);
        while (*it) {
            if ((*it)->checkState(0)==Qt::Checked){
                QString str="";
                str=QString("确认删除文件【%1】录吗？ 删除后是无法恢复的！！！！").arg((*it)->text(0));
                if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
                    str=QString("http://%1/up_file/movefile.php?%2/%3").arg(mySQL::ServerWEB).arg((*it)->text(1)).arg((*it)->text(0));
                    //QMessageBox::information(NULL, "文件名", str);
                    QSqlQuery query(mySQL::cn); //查询 表并输出，测试能否正常操作数据库
                    //先读取凭证总表
                    QString SQL="";
                    SQL=QString(" delete from upfiles where idd=%1").arg((*it)->text(3));
                    query.exec(SQL);
                    GetHTTP(str);
                }

            }
            ++it;
        }
        int PZH=ui->txtPZBH->text().toInt();
        LoadFJ(ui->cmbND->currentText().trimmed(),PZH);
}

void FormPZLR::on_btnFHRZ_clicked()
{
    //复核入账后凭证将不能修改
    QString str="";
    str=QString("确认复核入账处理吗？处理后将无法保存！！！！");
    if (QMessageBox::information(NULL, "提醒", str,QMessageBox::Yes | QMessageBox::No, QMessageBox::No)==QMessageBox::Yes){
        QDate currentdate = QDate::currentDate();
        QString NowDate = currentdate.toString("yyyy-MM-dd");
        QString PZBH=ui->txtPZBH->text();
        QString SQL="";
        SQL="update pzzb set ";//(type_id,nd,jzny,pzbh,pzlx,jzrq,dj,jz,fhrq,fh,xgrq) VALUES (";
        SQL+=QString("fh='%1',").arg(mySQL::UserName.trimmed().replace("'","''"));
        SQL+=QString("fhrq='%1'").arg(NowDate);
        SQL+=QString(" where type_id='%1'").arg(mySQL::TypeId.trimmed().replace("'","''"));
        SQL+=QString(" and nd='%1'").arg(ui->cmbND->currentText().trimmed().replace("'","''"));
        SQL+=QString(" and pzbh=%1").arg(PZBH);
        //QMessageBox::warning(this,"警告",SQL);
        //qDebug() << SQL;
        mySQL::cn.exec(SQL);
        LoadFJ(ui->cmbND->currentText().trimmed(),PZBH.toInt());
        ui->btnSave->setEnabled(false);
        QMessageBox::warning(this,"警告","复核入账成功！");
    }



}
